【发布时间】: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