【发布时间】:2016-12-09 14:49:38
【问题描述】:
感谢这里被问了很多次,但我似乎无法让它为我工作。
我写了一个刮板,它成功地从网站的第一页刮掉了我需要的一切。但是,我不知道如何让它循环浏览各个页面。
网址只是像这样 BLAH/3 + 'page=x' 递增
我学习编码的时间不长,所以任何建议都将不胜感激!
import requests
from bs4 import BeautifulSoup
url = 'http://www.URL.org/BLAH1/BLAH2/BLAH3'
soup = BeautifulSoup(r.content, "html.parser")
# String substitution for HTML
for link in soup.find_all("a"):
"<a href='>%s'>%s</a>" %(link.get("href"), link.text)
# Fetch and print general data from title class
general_data = soup.find_all('div', {'class' : 'title'})
for item in general_data:
name = print(item.contents[0].text)
address = print(item.contents[1].text.replace('.',''))
care_type = print(item.contents[2].text)
更新:
r = requests.get('http://www.URL.org/BLAH1/BLAH2/BLAH3')
for page in range(10):
r = requests.get('http://www.URL.org/BLAH1/BLAH2/BLAH3' + 'page=' + page)
soup = BeautifulSoup(r.content, "html.parser")
#print(soup.prettify())
# String substitution for HTML
for link in soup.find_all("a"):
"<a href='>%s'>%s</a>" %(link.get("href"), link.text)
# Fetch and print general data from title class
general_data = soup.find_all('div', {'class' : 'title'})
for item in general_data:
name = print(item.contents[0].text)
address = print(item.contents[1].text.replace('.',''))
care_type = print(item.contents[2].text)
更新 2!:
import requests
from bs4 import BeautifulSoup
url = 'http://www.URL.org/BLAH1/BLAH2/BLAH3&page='
for page in range(10):
r = requests.get(url + str(page))
soup = BeautifulSoup(r.content, "html.parser")
# String substitution for HTML
for link in soup.find_all("a"):
print("<a href='>%s'>%s</a>" % (link.get("href"), link.text))
# Fetch and print general data from title class
general_data = soup.find_all('div', {'class' : 'title'})
for item in general_data:
print(item.contents[0].text)
print(item.contents[1].text.replace('.',''))
print(item.contents[2].text)
【问题讨论】:
-
看看这个答案stackoverflow.com/questions/40809017/… 如果这对您没有帮助,请告诉我们。
-
循环你需要
while或for- 现在你没有它。 -
@daniboy000 - 抱歉,我似乎无法将其与我的联系起来! :s
-
谢谢@furas。这就是我现在正在看的,但似乎无法让它工作? r = requests.get(url+page) r = requests.get('URL.org/BLAH1/BLAH2/BLAH3?page=') # url next page soup = BeautifulSoup(r.content, "html.parser") url = 'URL.org/BLAH1/BLAH2/BLAH3?page=' for page in range (10): # 获取 10 个页面 r = requests.get(url+page)
-
抱歉@furas 不确定如何将 cmets 呈现为代码!
标签: python python-3.x web-scraping