我正在搜索一些衣服的网络,以获得他们的价格和他们的信息,每种产品可用,但与我的实际算法,它需要几天的时间来完成,并获得每个产品的每个不同的链接。例如,如果产品有5种颜色的5个链接,我有一个包含92k个条目和5k个产品的数据库,例如:
https://i.gyazo.com/410d4faa33e2fbccf8979c5399856dd3.png
https://i.gyazo.com/b6118e67205d153272df001fb5efcfc8.png
相同的产品ID (所以相同的产品),但链接不同。
所以我想要一些想法,以及如何实现它们来改善这一点,例如,我有产品ID,所以如果我已经访问了一个包含该ID的链接,我就不想再访问它了。我想抓取所有的网页,但只访问包含产品的网页……但我不知道如何实现这两个想法:/
这是我目前的代码(太慢了,有很多重复的代码):
import urllib
import urlparse
from itertools import ifilterfalse
from urllib2 import URLError, HTTPError
from bs4 import BeautifulSoup
urls = {"http://www.kiabi.es/"}
visited = set()
def get_html_text(url):
try:
return urllib.urlopen(current_url.encode('ascii','ignore')).read()
except (IOError,URLError, HTTPError, urllib.ContentTooShortError):
print "Error getting " + current_url
urls.add(current_url)
def find_internal_links_in_html_text(html_text, base_url):
soup = BeautifulSoup(html_text, "html.parser")
links = set()
for tag in soup.findAll('a', href=True):
url = urlparse.urljoin(base_url, tag['href'])
domain = urlparse.urlparse(base_url).hostname
if domain in url:
links.add(url)
return links
def is_url_already_visited(url):
return url in visited
while urls:
try:
word = '#C'
current_url = urls.pop()
print "Parsing", current_url
if word in current_url:
print "Parsing", current_url
htmltext= urllib.urlopen(current_url).read()
soup= BeautifulSoup(htmltext)
[get the product info and save it into a sql database]
html_text = get_html_text(current_url)
visited.add(current_url)
found_urls = find_internal_links_in_html_text(html_text, current_url)
new_urls = ifilterfalse(is_url_already_visited, found_urls)
urls.update(new_urls)
except Exception:
pass
例如,在爬虫中,我使用单词"#C“来知道这是一个产品页面并获取其信息,但我不知道如何区分该url是否具有我已经访问过的产品ID,我也不知道如何避免不相关的url,这就是为什么程序太慢并获得许多相等链接的原因。
谢谢你的帮助,任何你可以改进的地方都会很棒^^
发布于 2015-11-24 18:44:43
我推荐使用Scrapy。我的答案是基于它的强大功能。
引用你的疑问:
我不知道如何避免不相关的urls
回答:为了避免访问不相关的URL,您应该根据您的用例使用具有特定逻辑的爬行器。也就是说,您可以使用CrawlSpider并定义自己的Crawling rules,其中每个规则都定义了爬行站点的特定行为,这样您就不会访问不相关的URL。
下面是一个示例:http://doc.scrapy.org/en/latest/topics/spiders.html#crawlspider-example
...but我不知道如何区分该url是否有我已经访问过的产品ID……
回答:默认情况下,Scrapy使用RFPDupeFilter
作为其DUPEFILTER_CLASS
,用于检测和过滤重复请求。使用scrapy.utils.request.request_fingerprint
函数根据请求指纹进行RFPDupeFilter
过滤。
这是重复请求的Scrapy日志输出示例:
2015-11-23 14:26:48 [scrapy] DEBUG: Filtered duplicate request: <GET http://doc.scrapy.org/en/latest/topics/request-response.html> - no more duplicates will be shown (see DUPEFILTER_DEBUG to show all duplicates)
如果你还没有用过它,这里有一个Scrapy教程:http://doc.scrapy.org/en/latest/intro/tutorial.html
https://stackoverflow.com/questions/33874483
复制