【问题标题】:HTML acquired in Python code is not the same as displayed webpagePython代码中获取的HTML与显示的网页不一样
【发布时间】:2020-09-06 16:45:58
【问题描述】:

我最近开始使用Scrapy 学习网络抓取,作为练习,我决定从this url 抓取天气数据表。

通过检查页面的表格元素,我将其 XPath 复制到我的代码中,但在运行代码时我只得到一个空列表。我尝试使用以下代码检查 HTML 中存在哪些表:

from scrapy import Selector
import requests
import pandas as pd

url = 'https://www.wunderground.com/history/monthly/OIII/date/2000-5'
html = requests.get(url).content

sel = Selector(text=html)
table = sel.xpath('//table')

它只返回一个表,它不是我想要的。

经过一番研究,我发现这可能与页面源代码中的 JavaScript 渲染有关,Python requests 无法处理 JavaScript。

在经历了一些 SO Q&As 之后,我发现了一个 requests-html 库,它显然可以处理 JS 执行,所以我尝试使用以下代码 sn-p 获取表:

from requests_html import HTMLSession
from scrapy import Selector

session = HTMLSession()
resp = session.get('https://www.wunderground.com/history/monthly/OIII/date/2000-5')
resp.html.render()
html = resp.html.html

sel = Selector(text=html)
tables = sel.xpath('//table')

print(tables)

但结果没有改变。我怎样才能获得那张桌子?

【问题讨论】:

    标签: python html web-scraping scrapy


    【解决方案1】:

    问题

    这里可能存在多个问题——不仅是 javascript 执行,还有 HTML5 API、cookie、用户代理等。

    解决方案

    考虑将 Selenium 与无头 Chrome 或 Firefox Web 驱动程序一起使用。将 selenium 与 Web 驱动程序一起使用可确保按预期加载页面。无头模式确保您可以在不生成 GUI 浏览器的情况下运行代码——当然,您可以禁用无头模式以实时查看页面正在执行的操作,甚至添加断点,以便您可以在浏览器控制台中的 pdb 之外进行调试.

    示例代码:

    
    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    chrome_options = Options()
    chrome_options.add_argument("--no-sandbox")
    chrome_options.add_argument("--headless")
    
    driver = webdriver.Chrome(options=chrome_options)
    driver.get("https://www.wunderground.com/history/monthly/OIII/date/2000-5")
    
    tables = driver.find_elements_by_xpath('//table') # There are several APIs to locate elements available.
    
    print(tables)
    

    参考文献

    Selenium Github:https://github.com/SeleniumHQ/selenium

    Selenium (Python) 文档:https://selenium-python.readthedocs.io/getting-started.html

    定位元素:https://selenium-python.readthedocs.io/locating-elements.html

    【讨论】:

    • 不会标记为答案,因为我必须研究 selenium 以了解它的工作原理并显然修复一些 PATH 问题。不过非常感谢您的建议。
    • @FadeLights,当然。这是工作代码,所以如果它不适合你,请告诉我。
    【解决方案2】:

    您可以使用scrapy-splash 插件与Splash(scrapinghub 的javascript 浏览器)一起使用scrapy

    使用 splash 您可以渲染 javascript 并执行鼠标点击等用户事件

    【讨论】:

    • 感谢您的建议。如果可行,我会发表评论。
    猜你喜欢
    • 2019-03-28
    • 2012-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    • 2012-10-13
    • 1970-01-01
    • 2010-10-23
    相关资源
    最近更新 更多