使用请求modu时出现错误消息10054

2024-07-05 15:24:33 发布

您现在位置:Python中文网/ 问答频道 /正文

新来的程序员。在我学习python的时候,我试着浏览pof站点。试着用请求和漂亮的汤在网上拉屎。提前谢谢

错误似乎来自于行res=请求.get('https://www.pof.com/everyoneonline.aspx?page_id=%s'%pageId)

我试图删除分页页,只刮一页,但没用 也试着用时间。睡觉每次请求间隔3秒,但也没用

#Username and password 
username='MyUsername'
password='MyPassword'


#Login to pof site
from selenium import webdriver
import bs4,requests
browser = webdriver.Chrome(executable_path='/Users/Desktop/geckodriver-v0.24.0-win32/chromedriver.exe')
browser.get('https://www.pof.com')
linkElem= browser.find_element_by_link_text('Sign In')
linkElem.click()
usernameElem=browser.find_element_by_id('logincontrol_username')
usernameElem.send_keys(username)
passwordElem=browser.find_element_by_id('logincontrol_password')
passwordElem.send_keys(password)
passwordElem.submit()

#Webscraping online profile links from first 7 pagination pages
for pageId in range(7):
    res=requests.get('https://www.pof.com/everyoneonline.aspx?page_id=%s' %pageId)
    res.raise_for_status()
    soup= bs4.BeautifulSoup(res.text)
    profile = soup.findAll('div', attrs={'class' : 'rc'})
    for div in profile:
        print (div.findAll('a')['href'])

预期结果: 打印配置文件的所有href链接的列表,以便以后可以将它们保存到csv

实际结果: requests.exceptions.ConnectionError:('Connection aborted.',ConnectionResetError(10054,'An existing Connection was forced closed by the remote host',None,10054,None))enter code here


Tags: httpsbrowsercomidgetbywwwusername
1条回答
网友
1楼 · 发布于 2024-07-05 15:24:33

我会给你一些一般的信息,当刮网页:

  1. 首先,不要将请求与selenium一起使用!根据我的经验,90%的情况下,请求是最快和最简单的解决方案。在
  2. 始终尝试为您的请求提供标头。不提供标题会导致网页可疑,甚至可能会阻止您的所有请求(您得到的错误可能就是因为这个!)在
  3. 对于后续对网页的请求,请使用会话!,这样您的cookies将被存储,并且您实际上可以长期访问登录页面。在
  4. 这一个更客观,但是如果您已经了解regex,我建议使用re模块。BeautifulSoup很好,但是对于一般用途来说,re只是在我的经验中更容易。在

现在来回答你的问题吧,这里有很多不同的网页,但我建议你从所有网页中删除:

提取数据~


标题数据

  • 使用inspect element支持打开常用浏览器。转到要从中获取的网页并打开inspect element dock。在
  • 进入Network部分。在这里,您可以看到浏览器发出的所有请求,以及标题和源。在
  • 生成您想要模拟的请求,跟踪“网络”选项卡,转到包含所需的GET或在您的例子中是POST方法的请求。在
  • 复制该特定请求的请求头。您不需要所有这些(例如,cookie参数将由会话添加,因此本例中不需要它;同样,不需要以:开头的头,比如:method: POST
  • 将从浏览器复制的标题放到python dict中,下面是一个来自这个网页的示例:
headers = {
"accept": "application/json, text/javascript, */*; q=0.01",
"accept-encoding": "gzip, deflate, br",
"accept-language": "en-US,en;q=0.9,fa-IR;q=0.8,fa;q=0.7,de;q=0.6",
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"dnt": "1",
"origin": "https://stackoverflow.com",
"referer": "https://stackoverflow.com/questions/56399462/error-message-10054-when-wescraping-with-requests-module",
"user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) snap Chromium/74.0.3729.169 Chrome/74.0.3729.169 Safari/537.36",
}

过帐数据

  • 如果您想发出post请求,那么请求的Headers部分应该有另一个部分,名为“Payload”或“formdata”行。将其内容放入另一个python dict中,并根据需要更改其内容。在

使用数据~


现在您已经准备好将提取的数据用于python请求,然后在响应内容上使用re或{}来提取所需的数据。
在本例中,我登录到https://aavtrain.com/index.asp
试着按照我写的步骤来理解这里发生的事情:

^{pr2}$

我希望这对你有帮助,如果你有任何疑问,我会给你回电的。在

相关问题 更多 >