有漂亮汤的Python不会在页面中循环。
嘿,伙计们,这是我的第一篇帖子。我是一名营销人员(EWW),我是Python新手,所以请不要向我开枪 我通过反复试验来学习,破解像这样的脚本 谁能告诉我如何循环浏览网站的所有页面,然后打印每个url的信息有漂亮汤的Python不会在页面中循环。,python,beautifulsoup,Python,Beautifulsoup,嘿,伙计们,这是我的第一篇帖子。我是一名营销人员(EWW),我是Python新手,所以请不要向我开枪 我通过反复试验来学习,破解像这样的脚本 谁能告诉我如何循环浏览网站的所有页面,然后打印每个url的信息 url = "http://example.com" urls = [url] # Stack of urls to scrape visited = [url] # Record of scraped urls htmltext = urllib.urlopen(urls[0]).read
url = "http://example.com"
urls = [url] # Stack of urls to scrape
visited = [url] # Record of scraped urls
htmltext = urllib.urlopen(urls[0]).read()
# While stack of urls is greater than 0, keep scraping for links
while len(urls) > 0:
try:
htmltext = urllib.urlopen(urls[0]).read()
# Except for visited urls
except:
print urls[0]
# Get and Print Information
soup = BeautifulSoup(htmltext, "lxml")
urls.pop(0)
info = soup.findAll(['title', 'h1', 'h2', 'p'])
for script in soup("script"):
soup.script.extract()
print info
# Number of URLs in stack
print len(urls)
# Append Incomplete Tags
for tag in soup.findAll('a',href=True):
tag['href'] = urlparse.urljoin(url,tag['href'])
if url in tag['href'] and tag['href'] not in visited:
urls.append(tag['href'])
visited.append(tag['href'])
评论:
- 我看到
访问了
两次。在一个实例中,它用作URL列表,在另一个实例中用作HTML元素列表。这很淘气
- 在
循环中,每个url都从其站点请求并读取到while
中,禁止出现htmltext
异常。但是请注意,每次通过循环时,
之前的内容都会被覆盖并丢失。每次htmltext
可用时都必须调用BeautifulSoup,然后在再次创建htmltext
之前处理来自BeautifulSoup的soup
soup
import requests
import bs4
urls = ['url_1', 'url_2', 'url_3', 'url_4', 'url_5', 'url_6', 'url_7', 'url_8', 'url_9', 'url_10']
while urls:
url = urls.pop(0)
print (url)
try:
htmltext = requests.get(url).content
except:
print ('*** attempt to open '+url+' failed')
continue
soup = bs4.BeautifulSoup(htmltext, 'lxml')
title = soup.find('title')
print (title)
- 我使用请求库而不是urllib,因为它通常使生活更轻松
- 由于您使用
列表的url
方法删除其项目,因此我们不需要保留pop
访问的
url的记录。当它们从
中删除时,列表会变短,并最终变为空李>URL
询问而URL
是否为空URL
- 这段代码的要点是,它显示了查询远程站点和调用BeautifulSoup是如何在列表
的同一个循环中进行的URL
- 我看到
访问了
两次。在一个实例中,它用作URL列表,在另一个实例中用作HTML元素列表。这很淘气
- 在
循环中,每个url都从其站点请求并读取到while
中,禁止出现htmltext
异常。但是请注意,每次通过循环时,
之前的内容都会被覆盖并丢失。每次htmltext
可用时都必须调用BeautifulSoup,然后在再次创建htmltext
之前处理来自BeautifulSoup的soup
soup
import requests
import bs4
urls = ['url_1', 'url_2', 'url_3', 'url_4', 'url_5', 'url_6', 'url_7', 'url_8', 'url_9', 'url_10']
while urls:
url = urls.pop(0)
print (url)
try:
htmltext = requests.get(url).content
except:
print ('*** attempt to open '+url+' failed')
continue
soup = bs4.BeautifulSoup(htmltext, 'lxml')
title = soup.find('title')
print (title)
- 我使用请求库而不是urllib,因为它通常使生活更轻松
- 由于您使用
列表的url
方法删除其项目,因此我们不需要保留pop
访问的
url的记录。当它们从
中删除时,列表会变短,并最终变为空李>URL
询问而URL
是否为空URL
- 这段代码的要点是,它显示了查询远程站点和调用BeautifulSoup是如何在列表
的同一个循环中进行的URL