【发布时间】:2015-04-29 16:52:12
【问题描述】:
我正在尝试爬取网站的所有页面并提取某个标签/类的所有实例。
它似乎一遍又一遍地从同一页面提取信息,但我不知道为什么,因为 len(urls) #The stack of URL's being scraped 有一个钟形曲线变化,这让我觉得我至少在爬行通过链接,但我可能不正确地提取/打印信息。
import urllib
import urlparse
import re
from bs4 import BeautifulSoup
url = "http://weedmaps.com"
如果我尝试仅使用基本的 weedmaps.com URL,则不会打印任何内容,但如果我从一个页面开始,该页面具有我正在寻找的数据类型...url = "https://weedmaps.com/dispensaries/shakeandbake",那么它会提取信息,但它会一遍又一遍地打印相同的信息。
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)
urls.pop(0)
info = soup.findAll("div", {"class":"story-heading"})
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。希望这有助于更好地理解它。
标签: python web-scraping web-crawler beautifulsoup