【问题标题】:How to save the html source code while navigating to each link如何在导航到每个链接时保存 html 源代码
【发布时间】:2017-07-08 21:35:44
【问题描述】:

这是我的代码

driver = webdriver.Chrome()
path = "/home/winpc/test/python/dup/new"
def get_link_urls(url,driver):
    driver.get(url)
    url = urllib.urlopen(url)
    content = url.readlines() 
    urls = []
    for link in driver.find_elements_by_tag_name('a'):
        elem = driver.find_element_by_xpath("//*")
        source_code = elem.get_attribute("outerHTML")
        test = link.get_attribute('href')
        if str(test) != 'None':
               file_name=test.rsplit('/')[-1].split('.')[0]
               file_name_formated = file_name + "Copy.html"
               with open(os.path.join(path, file_name_formated), 'wb') as temp_file:
                    temp_file.write(source_code.encode('utf-8'))
        urls.append(link.get_attribute('href'))
    return urls

urls = get_link_urls("http://localhost:8080",driver)
sub_urls = []
for url in urls:
    if str(url) != 'None':
        sub_urls.extend(get_link_urls(url,driver))

此代码正确导航每个链接,但始终只复制第一个 html 页面。我需要保存每个页面导航的源代码。保存部分正在使用以下代码进行:

file_name_formated = file_name + "Copy.html"
with open(os.path.join(path, file_name_formated), 'wb') as temp_file:
                temp_file.write(source_code.encode('utf-8'))

【问题讨论】:

  • 那么您的具体问题是什么?

标签: python python-2.7 python-3.x selenium selenium-webdriver


【解决方案1】:

首先你在函数中一次又一次地覆盖 URL,所以修复那个。

通过selenium保存页面源,可以使用driver.page_source

此外,如果您希望此代码更快,请考虑使用 requests 模块。

response = requests.get(url).content

【讨论】:

  • 最好最简洁的方法是使用 BeautifulSoup 的美化功能。
  • 请提供完整的代码。这里的请求是什么?这里的内容是什么?
  • 其实我需要用动态改变的源页面保存
  • 在这种情况下,指定动态变化的确切内容。 requests 是一个 3rd 方模块,它就像一个更快、更强大的 urllib2 版本。 request.get(url).content 返回一个响应对象,其中包含 url 的页面源。
  • 在 py3 中,您需要对请求执行 .content.decode('utf-8')。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-05
  • 2012-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-29
相关资源
最近更新 更多