【发布时间】:2019-03-08 10:56:56
【问题描述】:
我使用multiprocessing.pool.ThreadPool 在python 中编写了一个脚本,以同时处理多个请求并执行稳健的抓取过程。解析器完美地完成了它的工作。
正如我在几个脚本中注意到的那样,当使用 multiprocessing 创建抓取过程时应该会有延迟,我想在我的下面的脚本也是如此。
但是,这就是我卡住的地方,找不到合适的位置来放置延迟。
到目前为止,这是我的脚本:
import requests
from urllib.parse import urljoin
from bs4 import BeautifulSoup
from multiprocessing.pool import ThreadPool
url = "http://srar.com/roster/index.php?agent_search=a"
def get_links(link):
completelinks = []
res = requests.get(link)
soup = BeautifulSoup(res.text,'lxml')
for items in soup.select("table.border tr"):
if not items.select("td a[href^='index.php?agent']"):continue
data = [urljoin(link,item.get("href")) for item in items.select("td a[href^='index.php?agent']")]
completelinks.extend(data)
return completelinks
def get_info(nlink):
req = requests.get(nlink)
sauce = BeautifulSoup(req.text,"lxml")
for tr in sauce.select("table[style$='1px;'] tr")[1:]:
table = [td.get_text(strip=True) for td in tr.select("td")]
print(table)
if __name__ == '__main__':
ThreadPool(20).map(get_info, get_links(url))
再说一次:我只需要知道脚本中的正确位置即可延迟。
【问题讨论】:
-
在您返回之前
return completelinks。 -
仍有两种方法可以延迟。你的意思是@stovfl?请查看 this image 进行澄清。非常感谢。
-
我们不喜欢图片! Edit 你的问题。 Edit您的问题并详细说明两种方式的pro和con?阅读Section: Lines and Indentation。
-
别误会@stovfl。我知道这里不接受图片。但是,我上传了该图片以确定您的意思。我提出这个问题(根据您的评论)只是因为您建议的延迟位置并不那么具体,因为我可以通过两种方式使用它。顺便说一下,我对缩进有点了解。
-
你对这两种方式的pro和con得出了哪个结论?
标签: python python-3.x multithreading web-scraping threadpool