Python Requests获取的HTML数据与浏览器不同; JS似乎无关紧要

时间:2018-02-15 18:54:20

标签: python html python-3.x web-scraping python-requests

我正试图从这个网站上搜集天气数据:

http://www.fastweather.com/yesterday.php?city=St.+Louis_MO

我遇到的问题是昨天的降水。在开发人员工具中查看时,我看到以下内容:

<strong>Yesterday's Precipitation</strong>
was 0.13 inches

但是当从Python中查看它时,无论是使用Requests还是urllib模块,我都会看到:

<strong>Yesterday\'s Precipitation</strong>
was T inches

我在浏览器中使用NoScript,但我不允许运行所有JavaScript,但仍会显示0.13。这个数字来自哪里,我如何用Python获得它?

我在Unix系统上,这将是每日运行的脚本。如果可能的话,我想避免使用Selenium。

即使有其他网站可供使用,我也想知道为什么存在神秘的T。

这是我的相关代码:

webpage = requests.get("http://www.fastweather.com/yesterday.php?city=St.+Louis_MO")
if webpage.status_code == 200:
    content = str(webpage.content)

我也试过这个:

with requests.Session() as session:
    webpage = session.get("http://www.fastweather.com/yesterday.php?city=St.+Louis_MO")
    content = webpage.text

而且:

webpage = urllib.request.urlopen("http://www.fastweather.com/yesterday.php?city=St.+Louis_MO")
content = webpage.read()

(上述代码中可能存在轻微错误,因为我无法确切记住每种方法的工作原理。)

1 个答案:

答案 0 :(得分:2)

您可以尝试以下代码来获取所需的输出:

import requests
from lxml import html

response = requests.get('http://www.fastweather.com/yesterday.php?city=St.+Louis_MO')
source = html.fromstring(response.text)
text_node = source.xpath('//div[@id="content"]//strong[.="Yesterday\'s Precipitation"]/following-sibling::text()[1]')[0]
print(text_node.strip())  # 'was 0.13 inches'