【问题标题】:Python Requests gets different HTML data than Browser; JS seems irrelevantPython Requests 获取的 HTML 数据与 Browser 不同; JS似乎无关紧要
【发布时间】:2018-02-15 18:54:20
【问题描述】:

我正在尝试从这个网站上抓取天气数据:

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()

(上面的代码可能有一些小错误,因为我不记得每个方法是如何工作的了。)

【问题讨论】:

  • 显示您的代码。使用 Requests 时我可以清楚地看到was 0.13 inches
  • 我添加了我的代码。

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


【解决方案1】:

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

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'

【讨论】:

  • 这行不通。我检查了 response.text,T 就在那里。或者使用 lxml.html.fromstring() 会以某种方式改变那个 T?
  • 不知道 :) 我无法重现您的问题并得到 "was T inches"... 我在输出中看到 "was 0.13 inches"
猜你喜欢
  • 2019-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多