python - 抓取 wsj.com 时页面上的元素不存在
问题描述
我正在使用 Python 来抓取网页。这是我的代码:
import requests
from bs4 import BeautifulSoup
# Set local variables
URL = 'https://www.wsj.com/market-data/bonds'
page = requests.get(URL)
soup = BeautifulSoup(page.content, 'html.parser')
# Get Master data table and Last update from URL
table = soup.find("table", attrs={"class": "WSJTables--table--1QzSOCfq "})
print(table)
该代码的结果是什么——我找不到表,也不知道为什么。
有什么建议么?
解决方案
你需要加上user-agent
header,否则页面会认为你是bot,会屏蔽你。另请注意,您的班级名称中有一个额外的空格
import requests
from bs4 import BeautifulSoup
URL = 'https://www.wsj.com/market-data/bonds'
HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36"
}
page = requests.get(URL, headers=HEADERS)
soup = BeautifulSoup(page.content, 'html.parser')
table = soup.find("table", attrs={"class": "WSJTables--table--1QzSOCfq"})
print(table)
推荐阅读
- node.js - 如何通过图像在网站中添加搜索选项
- c# - 如何处理 Xamarin.Android 中的“找不到资源 android:attr/android:progressBarStyleSmall”之类的错误?
- bit-manipulation - 使用位移/掩码从 4 位数中提取两个 2 位数
- javascript - 如何在 HTML 中将输入日期设置为当前日期
- javascript - 如何从 Ajax 内部的路由中获取 ID
- azure - 用于预配多个 Azure 负载均衡器以构建前端 IP 的 Terraform 代码
- javascript - Firebase 函数 onUpdate 不更新另一个文档“无法读取未定义的属性‘更新’”
- python - SQL 比较运算符问题)...在 '>'2021-06-01' AND 100*(d1_close-close)/close>'29'' at line 1" 附近使用正确的语法)
- rust - 如何将数字传递给 web3.eth().block()?
- php - 使用 PHP 发送电子邮件