【发布时间】:2018-09-01 14:47:09
【问题描述】:
我编写了一个脚本来抓取quotes to scrape 的引号和作者姓名。 在这个项目中,我使用 requests 来获取页面的代码和 bs4 来解析 HTML。 我使用while循环通过分页链接到下一页,但我希望我的代码在没有页面时停止运行。 我的代码有效,但不会停止运行。
这是我的代码:
from bs4 import BeautifulSoup as bs
import requests
def scrape():
page = 1
url = 'http://quotes.toscrape.com'
r = requests.get(url)
soup = bs(r.text,'html.parser')
quotes = soup.find_all('span',attrs={"class":"text"})
authors = soup.find_all('small',attrs={"class":"author"})
p_link = soup.find('a',text="Next")
condition = True
while condition:
with open('quotes.txt','a') as f:
for i in range(len(authors)):
f.write(quotes[i].text+' '+authors[i].text+'\n')
if p_link not in soup:
condition = False
page += 1
url = 'http://quotes.toscrape.com/page/{}'.format(page)
r = requests.get(url)
soup = bs(r.text,'html.parser')
quotes = soup.find_all('span',attrs={"class":"text"})
authors = soup.find_all('small',attrs={"class":"author"})
condition = True
else:
condition = False
print('done')
scrape()
【问题讨论】:
标签: python python-3.x web-scraping beautifulsoup request