python - 使用 Python 时无法在 chrome 开发工具中提取正确的元素

标签 python html css web-scraping beautifulsoup

我正在尝试使用 CSS 选择器从该站点访问日期,但它不允许我这样做。我不断收到此错误:AttributeError: 'NoneType' object has no attribute 'select'

import requests
from bs4 import BeautifulSoup
page = requests.get("https://www.accuweather.com/en/us/san- 
antonio/78205/daily-weather-forecast/351198")
soup = BeautifulSoup(page.content, 'html.parser')
daily = soup.find(class_="content-module")
period_tags = daily.select(".date .dow")
periods = [pt.get_text() for pt in period_tags]
periods

我希望输出以列表形式给我网页上的每一天

最佳答案

我只需要一个 User-Agent header 。但是,内容是动态生成的,因此您的请求响应 html 不会与可以运行 javascript 的网页上的相同。您可以使用正则表达式从响应中的 script 标记中提取所需的信息,然后使用 json 解析器进行解析

import requests, re , json

headers = {'User-Agent': 'Mozilla/5.0'}
r = requests.get('https://www.accuweather.com/en/us/san-%20antonio/78205/daily-weather-forecast/351198', headers=headers)
p = re.compile(r'var dailyForecast = (.*);')
data = json.loads(p.findall(r.text)[0])
#print(data)
forecasts = {i['dow'] + ' - ' + i['date']:i['day'] for i in data}
print(forecasts)
dows  = [i['dow'] for i in data]
print(dows)

关于python - 使用 Python 时无法在 chrome 开发工具中提取正确的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58576292/

相关文章:

python - 如何在 python (windows 7) 上安装模块

python - 如何从 Regex 中的字符串中找到不在单词边界的短语?

jquery - 使用 jquery 创建 div 元素并添加内部 html

html - 如何将 <article> 右对齐,以便下面的 <article> 保持在下方,并且我可以在该 <article> 的左侧放置图像?

javascript - 使用 transition-delay 选项 (css) 和 JS 使 div 移动

javascript - 用 chrome 去除触摸屏上的蓝色光标

python - libmysqlclient_r.18.dylib 与/usr/local/mysql/lib/MacOS 不同

HTML/CSS 嵌套有序列表

javascript - 无限循环中的字体颜色变化

python - 为另一列中的每个唯一值创建一个具有唯一值的列