python-3.x - 我得到 ConnectionResetError: [Errno 54] Connection reset by peer 在尝试抓取时
问题描述
任何人都可以帮助我吗?我在尝试使用 BeautifulSoup 抓取时遇到这些错误,
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen as uReq
myUrl = "https://www.tokopedia.com/discovery/produk-terlaris?source=homepage.top_carousel.0.38454"
#open the connection
uClient = uReq(myUrl)
page_html = uClient.read()
uClient.close()
page_soup = soup(page_html,"html.parser")
product = page_soup.findAll("div", {"class": "css-6bc98m e1uv83qc1"})
print(len(product))
这就是错误
Traceback (most recent call last):
....
....
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/ssl.py", line 911, in read
return self._sslobj.read(len, buffer)
ConnectionResetError: [Errno 54] Connection reset by peer
解决方案
首先,您需要User-Agent
标头,否则服务器(正确)认为您是机器人。
第二件事是你不会从那个网站得到任何东西,因为几乎所有的内容都在后面JS
(JavaScript),这基本上意味着BeautifulSoup
看不到它。
我已经修复了您的代码,因此不再有错误,但是,正如我所说,您在HTML
返回时没有任何 div。
import requests
from bs4 import BeautifulSoup
my_url = "https://www.tokopedia.com/discovery/produk-terlaris?source=homepage.top_carousel.0.38454"
headers = {
"user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36",
}
page_soup = BeautifulSoup(requests.get(my_url, headers=headers).text, "html.parser")
product = page_soup.findAll("div", {"class": "css-6bc98m e1uv83qc1"})
print(len(product))
这打印0
。
您可以做的是探索selenium
或检查流量,看看是否有 API 端点暴露。
推荐阅读
- go - 类型为 interface{} 时初始化 nil 指针
- tooltip - Oracle APEX 20.1 - 自定义字段帮助/工具提示
- google-apps-script - 使用 Google Apps 脚本查找特定值,然后在同一行中填充单元格
- regex - 正则表达式不匹配字符串中的确切单词
- java - 我在构建应用程序时在 android studio 中遇到了 Android 资源链接失败错误。我不知道如何解决这个问题。我是 Android Studio 的新手
- javascript - 仅当屏幕宽度> 1250px时如何执行脚本
- flutter - DropdownButtonFormField 导致 RenderFlex 溢出
- flutter - 如何在颤振中集成 facebook 登录?
- powershell - 即使加载程序集,SMO Powershell 也会损坏
- r - 如何在 R 中读取 SharePoint 列表(本地)