在python中获取下一页网址
问题描述:
现在我试图从网页上刮掉所有的url。它共有5个类别,每个类别都有不同的页面(每页有10篇文章)。在python中获取下一页网址
例如:
Categories Pages
Banana 5
Apple 14
Cherry 7
Melon 6
Berry 2
代码:
import requests
from bs4 import BeautifulSoup
import re
from urllib.parse import urljoin
res = requests.get('http://www.abcde.com/SearchParts')
soup = BeautifulSoup(res.text,"lxml")
href = [ a["href"] for a in soup.findAll("a", {"id" : re.compile("parts_img.*")})]
b1 =[]
for url in href:
b1.append("http://www.abcde.com"+url)
print (b1)
从主页 “http://www.abcde.com/SearchParts” 我可以凑每个类别的第一页的URL。 b1是首页的网址列表。
像这样:
Categories Pages url
Banana 1 http://www.abcde.com/A
Apple 1 http://www.abcde.com/B
Cherry 1 http://www.abcde.com/C
Melon 1 http://www.abcde.com/E
Berry 1 http://www.abcde.com/F
然后我用B1的源代码来凑下一个页面的网址。所以b2是第二页网址的列表。
代码:
b2=[]
for url in b1:
res2 = requests.get(url).text
soup2 = BeautifulSoup(res2,"lxml")
url_n=soup2.find('',rel = 'next')['href']
b2.append("http://www.abcde.com"+url_n)
print(b2)
像这样:
Categories Pages url
Banana 1 http://www.abcde.com/A/s=1&page=2
Apple 1 http://www.abcde.com/B/s=9&page=2
Cherry 1 http://www.abcde.com/C/s=11&page=2
Melon 1 http://www.abcde.com/E/s=7&page=2
Berry 1 http://www.abcde.com/F/s=5&page=2
现在,当我尝试做第三个,这是一个错误,因为贝瑞的第二页是最后一页,它有没有“下“在源代码中。特别是当每个类别都有不同的页面/网址时,我该怎么做?
整个代码(直到它遇到错误):自那以后
import requests
from bs4 import BeautifulSoup
import re
from urllib.parse import urljoin
res = requests.get('http://www.ca2-health.com/frontend/SearchParts')
soup = BeautifulSoup(res.text,"lxml")
href = [ a["href"] for a in soup.findAll("a", {"id" : re.compile("parts_img.*")})]
b1 =[]
for url in href:
b1.append("http://www.ca2-health.com"+url)
print (b1)
print("===================================================")
b2=[]
for url in b1:
res2 = requests.get(url).text
soup2 = BeautifulSoup(res2,"lxml")
url_n=soup2.find('',rel = 'next')['href']
b2.append("http://www.ca2-health.com"+url_n)
print(b2)
print("===================================================")
b3=[]
for url in b2:
res3 = requests.get(url).text
soup3 = BeautifulSoup(res3,"lxml")
url_n=soup3.find('',rel = 'next')['href']
b3.append("http://www.ca2-health.com"+url_n)
print(b3)
并在此之后,我会让B1,B2,B3和......作为一个名单,我将拥有所有从该页面的网址。提前致谢。
答
如果您发布错误追溯,这将有所帮助。但我猜你得到KeyError
。处理异常并继续循环。如果您收到KeyError
做到以下几点:
try:
url_n=soup3.find('',rel = 'next')['href']
except KeyError:
continue
OR
try:
url_n=soup3.find('',rel = 'next').get('href')
except AttributeError:
continue
让我知道,如果这有助于。