Web scraping 使用Beautifulsoup在python中刮取下一页
我想从每一页抓取链接,然后转到下一页,并做同样的事情。以下是我从第一页抓取链接的代码:Web scraping 使用Beautifulsoup在python中刮取下一页,web-scraping,beautifulsoup,Web Scraping,Beautifulsoup,我想从每一页抓取链接,然后转到下一页,并做同样的事情。以下是我从第一页抓取链接的代码: import requests from bs4 import BeautifulSoup page='https://www.booli.se/slutpriser/goteborg/22/?objectType=L%C3%A4genhet' request = requests.get(page) soup = BeautifulSoup(request.text,'lxml') li
import requests
from bs4 import BeautifulSoup
page='https://www.booli.se/slutpriser/goteborg/22/?objectType=L%C3%A4genhet'
request = requests.get(page)
soup = BeautifulSoup(request.text,'lxml')
links= soup.findAll('a',class_='search-list__item')
url=[]
prefix = "https://www.booli.se"
for link in links:
url.append(prefix+link["href"])
我在前三页尝试了以下内容,但没有成功
import re
import requests
from bs4 import BeautifulSoup
url=[]
prefix = "https://www.booli.se"
with requests.Session() as session:
for page in range(4):
response = session.get("https://www.booli.se/slutpriser/goteborg/22/?
objectType=L%C3%A4genhet&page=%f" % page)
soup = BeautifulSoup(response.content, "html.parser")
links= soup.findAll('a',class_='search-list__item')
for link in links:
url.append(prefix+link["href"])
首先,您必须创建可以在一个页面上正常工作的代码 然后,您必须将您的刮码放入循环中
url = "https://www.booli.se/slutpriser/goteborg/22/?objectType=L%C3%A4genhet&page=1"
while True:
code goes here
您会注意到链接末尾有一个page=编号。
您必须考虑通过更改page=number在这些url上运行循环
i=1
url = "https://www.booli.se/slutpriser/goteborg/22/?objectType=L%C3%A4genhet&page=" + str(i)
while True:
i = i+1
page = requests.get(url)
if page.status_code != 200:
break
url = "https://www.booli.se/slutpriser/goteborg/22/?objectType=L%C3%A4genhet&page=" + str(i)
#Your scraping code goes here
#
#
我使用了if语句,这样循环就不会永远运行。它将转到最后一页。是的,我做了。非常感谢。以下是前两页的代码:
urls=[]
for page in range(3):
urls.append("https://www.booli.se/slutpriser/goteborg/22/?
objectType=L%C3%A4genhet&page={}".format(page))
page=urls[1:]
#page
import requests
from bs4 import BeautifulSoup
inturl=[]
for page in page:
request = requests.get(page)
soup = BeautifulSoup(request.text,'lxml')
links= soup.findAll('a',class_='search-list__item')
prefix = "https://www.booli.se"
for link in links:
inturl.append(prefix+link["href"])
发生了什么错误或什么不起作用?您只做了几次。如果你想刮去所有的页面,你需要重复这样做,只要你找到一个新的
url
。这是一个小规模的例子。如果我能让它在3个页面上正常工作,我可以在以后运行一个更大的循环。问题就在这里,我希望它能转到下一页,但它没有做到。将requests.Session()作为会话:用于范围(4)中的页面:response=Session.get(“?objectType=L%C3%A4genhet&page=%f”%page)soup=BeautifulSoup(response.content,“html.parser”)我移动到下一页的循环没有通过。我觉得所有的4页都是一样的。response=session.get(“https://www.booli.se/slutpriser/goteborg/22/? objectType=L%C3%A4genhet&page=%f”%page)
将此行更改为response=session.get("https://www.booli.se/slutpriser/goteborg/22/? objectType=L%C3%A4genhet&page=“+str(page))
不管你说什么,他已经做了。这对他没有帮助,也不是答案。此外,你正在添加str(i)
每次使用url
都是不正确的。我使用了这种策略进行刮取,效果很好。不要只是命令给出有用的解决方案