python 多线程爬取网站数据利用线程池

Python07

python 多线程爬取网站数据利用线程池,第1张

"""

@author: wangxingchun

多线程(线程池)

下载数据

"""

import requests

import csv

from concurrent.futures import ThreadPoolExecutor as tp

#创建一个csv文件,注意创建writer对象"csv.writer()"

f = open('xinfadi.csv','w',encoding='utf8')

csvwrite = csv.writer(f)

#如果写入txt文件,不需要创建writer对象。

# f = open('xinfadidata.txt','w',encoding='utf8')

#创建一个函数,以页码做为参数

def down(n_page):

url = 'http://www.xinfadi.com.cn/getPriceData.html'

data = {'count': 428225,'current': n_page,'limit': 20}

resp = requests.post(url,data=data)

datas =resp.json()

#通过分析数据嵌套情况,获取数据。此处可在网页开发工具json数据中查看分析。

for i in range(len(datas['list'])):

name = datas['list'][i]['prodName']

highPrice = datas['list'][i]['highPrice']

lowPrice = datas['list'][i]['lowPrice']

pubDate = datas['list'][i]['pubDate']

place = datas['list'][i]['place']

csvwrite.writerow((name,highPrice,lowPrice,pubDate,place))#writerow要求写入的是可迭代对象

# f.writelines(f'{name},{highPrice},{lowPrice},{pubDate},{place} ')

resp.close()

if __name__ == '__main__':

with tp(50) as t: #创建线程池,

for n in range(1,101): #遍历数据网页

t.submit(down,n) #提交给线程池,进行多线程下载

print(f'共{n}页数据下载完毕!')

f.close()

如果您使用 Python 从网页中抓取数据并将其保存到 Excel 文件,但 Excel 文件不包含任何数据,则可能有多种原因。以下是一些可能的原因和解决方案:

您没有使用正确的方法将数据写入 Excel 文件。若要将数据保存到 Excel 文件,需要使用库,例如 或 。这些库提供可用于创建和写入 Excel 文件的函数和类。确保已导入正确的库,并使用正确的方法将数据写入文件。openpyxlxlsxwriter

将数据写入 Excel 文件后,您不会保存该文件。将数据写入 Excel 文件后,需要使用 or 方法保存对文件的更改。如果不保存文件,则不会保留写入文件的数据。save()save_as()

您没有在正确的模式下打开 Excel 文件。使用 Python 打开 Excel 文件时,需要指定是要读取文件还是写入文件。如果以只读模式打开文件,则无法向其写入数据。确保在写入模式下打开文件,在调用该方法时使用该选项。write_onlyopen()

您没有将数据写入 Excel 文件中的正确工作表。一个 Excel 文件可以包含多个工作表,您需要指定要将数据写入哪个工作表。请确保在调用 or 方法将数据写入 Excel 文件时使用正确的工作表名称。append()write()

回答不易望请采纳

一,检查pip有没安装cryptography,pyOpenSSL,certifi

pip install cryptography

pip install pyOpenSSL

pip install certifi

二,添加ssl验证

import ssl

ssl._create_default_https_context = ssl._create_stdlib_context

三,添加header

header = {

"User-Agent":"Mozilla/5.0 (Windows NT 10.0Win64x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.72 Safari/537.36 Edg/89.0.774.45"

}

四,调用requests的get接口

response = requests.get(url,headers=header)

content = response.text

print(content)

就能获取到html内容,如果需要更好的解释html标签内容可以使用 BeautifulSoup