【发布时间】:2021-01-06 16:47:36
【问题描述】:
一段时间以来,我一直在使用 Selenium 来抓取网站,但由于某些原因,它不再工作了。我使用 Selenium 是因为您需要与网站交互才能翻阅页面(即:单击下一步按钮)。
作为解决方案,我正在考虑使用 Requests 中的 Post 方法。我不确定它是否可行,因为我从未使用过 Post 方法,而且我不熟悉它的作用(尽管我有点理解一般概念)。
我的代码看起来像这样:
import requests
from bs4 import BeautifulSoup
headers = {"User-Agent":
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10 11 5) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/50.0.2661.102 Safari/537.36"}
url = "https://www.centris.ca/fr/propriete~a-vendre?view=Thumbnail"
def infinity():
while True:
yield
c = 0
urls = []
for i in infinity():
c += 1
page = list(str(soup.find("li",{"class":"pager-current"}).text).split())
pageTot = int("".join(page[-2:])) # Check the total number of page
if c <= pageTot: # Scrape the first page
if c <= 1:
req = requests.get(url, headers=headers)
else:
pass
# This is where I'm stuck but ideally I'd be using Post method in some way
soup = BeautifulSoup(req.content,"lxml")
for link in soup.find_all("a",{"class":"a-more-detail"}):
try: # For each page scrape ads url
urls.append("https://www.centris.ca" + link["href"])
except KeyError:
pass
else: # When all pages are scrape exit the loop
break
for url in list(dict.fromkeys(urls)):
pass # do stuff
这是在网页上单击下一步时发生的情况:
这是请求(startPosition 从第 1 页的 0 开始,并以 12 的跳跃增加)
这是响应的一部分:
{"d":{"Message":"","Result":{"html": [...], "count":34302,"inscNumberPerPage":12,"title":""},"Succeeded":true}}
有了这些信息,是否可以使用 Post 方法来抓取每一页?我怎么能这样做?
【问题讨论】:
标签: python html post web-scraping python-requests