【发布时间】:2026-01-23 18:00:01
【问题描述】:
我使用 python 创建了一个脚本来解析遍历多个页面的不同项目的链接。为了解析来自它的登录页面的链接,get requests 也可以,所以我在第一页使用了get requests。
但是,需要发出带有适当参数的发布请求才能从下一页获取链接。我也这样做了。该脚本现在可以解析最多 11 个页面的链接。 在第 12 页之后出现问题,以此类推。该脚本不再起作用。我尝试了不同的页面,例如 20,50,100,150。没有成功。
我试过了:
import time
import requests
from bs4 import BeautifulSoup
res_url = 'https://www.brcdirectory.com/InternalSite//Siteresults.aspx?'
params = {
'CountryId': '0',
'CategoryId': '49bd499b-bc70-4cac-9a29-0bd1f5422f6f',
'StandardId': '972f3b26-5fbd-4f2c-9159-9a50a15a9dde'
}
with requests.Session() as s:
page = 11
while True:
print("**"*5,"trying with page:",page)
req = s.get(res_url,params=params)
soup = BeautifulSoup(req.text,"lxml")
if page==1:
for item_link in soup.select("h4 > a.colorBlue[href]"):
print(item_link.get("href"))
else:
payload = {i['name']:i.get('value') for i in soup.select('input[name]')}
payload['__EVENTTARGET'] = 'ctl00$ContentPlaceHolder1$gv_Results'
payload['__EVENTARGUMENT'] = f"{'Page$'}{page}"
payload['ctl00$ContentPlaceHolder1$ddl_SortValue'] = 'SiteName'
res = s.post(res_url,params=params,data=payload)
sauce = BeautifulSoup(res.text,"lxml")
if not sauce.select("h4 > a.colorBlue[href]"):break
for elem_link in sauce.select("h4 > a.colorBlue[href]"):
print(elem_link.get("href"))
page+=1
time.sleep(3)
如何使用请求在 11 页后抓取链接?
【问题讨论】:
-
“它不起作用”是什么意思?网络服务器是否返回一些错误?会发生什么?
-
不。没有错误。就像我定义了这一行
if not sauce.select("h4 > a.colorBlue[href]"):break一样优雅地退出,否则循环继续进行而不解析任何内容。 -
你检查最后一页的内容了吗?它可能会提供线索。此外,检查最后一个请求的状态代码和返回的标头。
-
在页面
12及以后的状态为500,这是标题{'Cache-Control': 'private', 'Content-Type': 'text/html; charset=utf-8', 'Server': 'Microsoft-IIS/7.5', 'X-AspNet-Version': '4.0.30319', 'X-Powered-By': 'ASP.NET', 'Date': 'Sat, 12 Oct 2019 20:08:32 GMT', 'Content-Length': '104058'} -
500 是内部服务器错误。可能最后一页的内容包含错误信息。
标签: python python-3.x post web-scraping