python-3.x - 抓取时未从网站获取适当的汤对象
问题描述
我正在尝试使用 BeautifulSoup 和请求来抓取雅虎财经网站,但没有得到正确的汤。它给了我一个 404 page not found html 代码,而不是给我网站的原始 html 代码。这是我的代码。
from bs4 import BeautifulSoup
import requests
soup = BeautifulSoup(requests.get('https://finance.yahoo.com/quote/FBRX/profile?p=FBRX').text, 'lxml')
print(soup)
你能帮我抓取这个网站吗?
解决方案
尝试设置User-Agent
HTTP 标头以从服务器获得正确的响应:
import requests
from bs4 import BeautifulSoup
url = "https://finance.yahoo.com/quote/FBRX/profile?p=FBRX"
headers = {
"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:92.0) Gecko/20100101 Firefox/92.0"
}
soup = BeautifulSoup(requests.get(url, headers=headers).content, "html.parser")
print(soup.h1.text)
印刷:
Forte Biosciences, Inc. (FBRX)
推荐阅读
- javascript - 传递超过一定长度的对象数组时,AJAX POST 数据到 ASP.NET Core 中的 MVC 控制器始终为空
- c# - asp.netcore 中的 Automapper 用于请求和响应
- postgresql - 在 PostgreSQL 12 中,如果查询包含在子表中,通过继承创建分区是否会提高查询性能?
- sql - 使用过程 oracle 运行时合并更新不起作用
- sql - 从 cols 列表中查找表列表
- c# - 编辑和删除 asp:commandfield 在 gridview 转换为 asp:templatefield 后停止工作
- sql-server - 向 SQL Azure 中的现有表添加标识列/主键
- java - 深度优先搜索递归调用导致 StackOverflow 错误
- html - 使自动生成的 flexbox 行的背景颜色为 100% 宽度
- verilog - Verilog 测试台错误多路复用 4x1 使用 EDAPlayground