gpt4 book ai didi

python - 简单的网络爬虫非常慢

转载 作者:太空宇宙 更新时间:2023-11-04 02:53:33 24 4
gpt4 key购买 nike

我构建了一个非常简单的网络爬虫来爬取下面 URL 中的约 100 个小 json 文件。问题是爬虫需要一个多小时才能完成。考虑到 json 文件有多小,我发现这很难理解。我在这里做错了什么吗?

def get_senate_vote(vote):
URL = 'https://www.govtrack.us/data/congress/113/votes/2013/s%d/data.json' % vote
response = requests.get(URL)
json_data = json.loads(response.text)
return json_data

def get_all_votes():
all_senate_votes = []
URL = "http://www.govtrack.us/data/congress/113/votes/2013"
response = requests.get(URL)
root = html.fromstring(response.content)
for a in root.xpath('/html/body/pre/a'):
link = a.xpath('text()')[0].strip()
if link[0] == 's':
vote = int(link[1:-1])
try:
vote_json = get_senate_vote(vote)
except:
return all_senate_votes
all_senate_votes.append(vote_json)

return all_senate_votes

vote_data = get_all_votes()

最佳答案

这是一个相当简单的代码示例,我计算了每次调用所花费的时间。在我的系统上,每个请求平均花费 2 秒,并且有 582 个页面要访问,因此大约 19 分钟,而无需将 JSON 打印到控制台。在您的情况下,网络时间加上打印时间可能会增加。

#!/usr/bin/python

import requests
import re
import time
def find_votes():
r=requests.get("https://www.govtrack.us/data/congress/113/votes/2013/")
data = r.text
votes = re.findall('s\d+',data)
return votes

def crawl_data(votes):
print("Total pages: "+str(len(votes)))
for x in votes:
url ='https://www.govtrack.us/data/congress/113/votes/2013/'+x+'/data.json'
t1=time.time()
r=requests.get(url)
json = r.json()
print(time.time()-t1)
crawl_data(find_votes())

关于python - 简单的网络爬虫非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43138612/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com