我正在用Django web框架用Python制作一个网络抓取应用程序。我需要用漂亮的汤库抓取多个查询。下面是我写的代码的快照:
for url in websites:
r = requests.get(url)
soup = BeautifulSoup(r.content)
links = soup.find_all("a", {"class":"dev-link"})实际上,网页的抓取是按顺序进行的,我想以并行的方式运行它。我对Python中的线程化不是很了解。谁能告诉我,我怎样才能并行抓取?任何帮助都将不胜感激。
发布于 2017-05-29 23:08:55
尝试此解决方案。
import threading
def fetch_links(url):
r = requests.get(url)
soup = BeautifulSoup(r.content)
return soup.find_all("a", {"class": "dev-link"})
threads = [threading.Thread(target=fetch_links, args=(url,))
for url in websites]
for t in thread:
t.start()通过requests.get()下载网页内容是一种阻塞操作,Python线程化实际上可以提高性能。
发布于 2017-05-29 23:09:40
如果你想使用多线程,
import threading
import requests
from bs4 import BeautifulSoup
class Scraper(threading.Thread):
def __init__(self, threadId, name, url):
threading.Thread.__init__(self)
self.name = name
self.id = threadId
self.url = url
def run(self):
r = requests.get(self.url)
soup = BeautifulSoup(r.content, 'html.parser')
links = soup.find_all("a")
return links
#list the websites in below list
websites = []
i = 1
for url in websites:
thread = Scraper(i, "thread"+str(i), url)
res = thread.run()
# print res这可能会有帮助
发布于 2017-05-29 23:29:53
当涉及到python和scraping时,scrapy可能是最佳选择。
scrapy使用twisted mertix库来实现并行性,因此您不必担心线程和python GIL
如果您必须使用漂亮的must,请查看this library
https://stackoverflow.com/questions/44245451
复制相似问题