python - 使用 Python 时无法在 chrome 开发工具中提取正确的元素
问题描述
我正在尝试使用 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 标头。但是,内容是动态生成的,因此您的请求响应 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)
推荐阅读
- .net - 实现 IComparable
在泛型中:如何访问泛型的值? - java - 为什么 replaceAll() 删除一个额外的字符
- python - 基于python中的逻辑表达式使用for循环创建新列
- html - 如何将视频和图片放在同一位置?
- javascript - 在嵌套的 Gridview 中展开全部的 JQuery 代码
- swift - 崩溃 - “无法将 'NSTaggedPointerString' (0x10ec9b560) 类型的值转换为 'NSDictionary' (0x10ec9b880)”
- c# - 在 Azure 函数中使用 RestSharp 调用 HTTPS 会给出“无法建立 SSL 连接”
- hive - Hive 分隔符 'field.delim' = '1'
- angular-material - colSpan 和 row Span 如何添加到材料表 Header Angular 7?
- javascript - 如何获取语义用户日历当前显示的月份和年份?