【问题标题】:Cannot extract correct element in chrome dev tools when using Python使用 Python 时无法在 chrome 开发工具中提取正确的元素
【发布时间】:2020-02-22 20:31:37
【问题描述】:

我正在尝试使用 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":'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML , 像壁虎) Chrome/77.0.3865.120 Safari/537.36'}

标签: python html css web-scraping beautifulsoup


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-10
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 2021-10-16
    • 1970-01-01
    • 2015-03-24
    • 1970-01-01
    相关资源
    最近更新 更多