【发布时间】:2023-03-26 18:25:01
【问题描述】:
我一直在做一个简单的网络爬虫程序来学习如何编码,我让它工作了,但我想看看如何让它更快。我想问我如何为这个程序实现多线程?该程序所做的只是打开股票代码文件并在线搜索该股票的价格。
这是我的代码
import urllib.request
import urllib
from threading import Thread
symbolsfile = open("Stocklist.txt")
symbolslist = symbolsfile.read()
thesymbolslist = symbolslist.split("\n")
i=0
while i<len (thesymbolslist):
theurl = "http://www.google.com/finance/getprices?q=" + thesymbolslist[i] + "&i=10&p=25m&f=c"
thepage = urllib.request.urlopen(theurl)
# read the correct character encoding from `Content-Type` request header
charset_encoding = thepage.info().get_content_charset()
# apply encoding
thepage = thepage.read().decode(charset_encoding)
print(thesymbolslist[i] + " price is " + thepage.split()[len(thepage.split())-1])
i= i+1
【问题讨论】:
-
你能展示一下 stocklist.txt 的样子吗
-
它只是一个包含所有股票名称的文本文档。是这样的:ABY ABEO ABEOW ABIL ABMD AXAS ACIA ACTG 等等,每个后面都有一个 ENTER
-
也尝试使用请求。比 urllib 好
-
urllib.request 不一样吗?
标签: python multithreading python-3.x web-scraping