首页 > 解决方案 > 使用 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

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

标签: pythonhtmlcssweb-scrapingbeautifulsoup

解决方案


我只需要一个 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)

推荐阅读