我试图从数千页的页面中抓取数据。我的代码工作正常约100页,但后来显着减慢。我很确定我的Tarzan-like代码可以改进,这样网页捕获过程的速度就会提高。任何帮助,将不胜感激。 TIA!优化此Python代码 - 网页扫描并将结果输出到CSV文件
下面是简化的代码:
csvfile=open('test.csv', 'w', encoding='cp850', errors='replace')
writer=csv.writer(csvfile)
list_url= ["http://www.randomsite.com"]
i=1
for url in list_url:
base_url_parts = urllib.parse.urlparse(url)
while True:
raw_html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(raw_html, "lxml")
#### scrape the page for the desired info
i=i+1
n=str(i)
#Zip the data
output_data=zip(variable_1, variable_2, variable_3, ..., variable_10)
#Write the observations to the CSV file
writer=csv.writer(open('test.csv','a',newline='', encoding='cp850', errors='replace'))
writer.writerows(output_data)
csvfile.flush()
base="http://www.randomsite.com/page"
base2=base+n
url_part2="/otherstuff"
url_test = base2+url_part2
try:
if url_test != None:
url = url_test
print(url)
else:
break
except:
break
csvfile.close()
编辑:感谢所有的答案,我学到了很多,从他们。我(慢慢地)学习了Scrapy的方式。但是,我发现这些页面可以通过批量下载获得,这将是解决性能问题的更好方法。
如果你的代码有效,但可以使用一些imprvement,代码审查论坛是地方。 [HTTP://codereview.stackexchange。com/questions/tagged/python] –
啊,好的,我不知道这个资源。谢谢,我会在那里发帖。 –