我正在使用Django Web框架在Python中创建一个webscraping应用程序。我需要使用beautifulsoup库废弃多个查询。以下是我编写的代码快照:
for url in websites:
r = requests.get(url)
soup = BeautifulSoup(r.content)
links = soup.find_all("a", {"class":"dev-link"})
实际上这里的网页抓取是顺序进行的,我想以并行的方式运行它。我不太了解Python中的线程。 谁能告诉我,我怎么能以平行方式做废料?任何帮助,将不胜感激。
答案 0 :(得分:0)
您可以使用hadoop(http://hadoop.apache.org/)并行运行您的作业。这是运行并行任务的非常好的工具。
答案 1 :(得分:0)
尝试此解决方案。
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线程实际上可以提高性能。
答案 2 :(得分:0)
如果你想使用多线程,
import threading
import requests
from bs4 import BeautifulSoup
class Scrapper(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 = Scrapper(i, "thread"+str(i), url)
res = thread.run()
# print res
这可能会有所帮助
答案 3 :(得分:0)
当谈到python和抓取时,scrapy可能是要走的路。
scrapy使用twisted mertix库进行并行操作,因此您不必担心线程和python GIL
如果您必须使用beautifulsoap检查this library