mport os
import re
from uuid import uuid1
import requests
from bs4 import BeautifulSoup
from random import choice
import urllib3
import json
# 获取随机请求头
def get_headers():
file = open('../../tools/user_agent.txt', 'r')
user_agent_list = file.readlines()
user_agent = str(choice(user_agent_list)).replace('\n', '')
user_agent = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:39.0) Gecko/20100101 Firefox/39.0' if len(
user_agent) < 10 else user_agent
headers = {
"User-Agent": user_agent,
}
return headers
# 负责下载图片
def download(url, end,fileName):
try:
headers = get_headers()
response = requests.get(url, headers=headers)
# 获取的文本实际上是图片的二进制文本
img = response.content
path = "c:/pdf-2020-10-9/" + fileName + end
print(url)
# 将他拷贝到本地文件 w 写 b 二进制 wb代表写入二进制文本
with open(path, 'wb') as f:
f.write(img)
except Exception as e:
print(str(e))
pass
def requests_get(url):
try:
url_prefix='http://static.sse.com.cn'
headers = get_headers()
# 请求页面
__http = urllib3.PoolManager()
headers={'Content-Type': 'application/json','Referer':''}
resp = __http.request('get', targetUrl,headers=headers)
# 解析
dataDic =json.loads(resp.data.decode('utf-8'))
pdf_list=dataDic['pageHelp']['data']
for pdf in pdf_list:
print(pdf)
# 获取图片链接
code= pdf['SECURITY_CODE']
name = pdf["SECURITY_NAME"]
url = pdf["URL"]
url = url_prefix+url
ssedate = pdf['SSEDATE']
title = pdf['TITLE']
title = re.sub(r'[/\:*?"<>|]', '', title)
# 获取图片后缀
fullFileName = os.path.split(url)[1]
fileName=os.path.splitext(fullFileName)[0]
end = os.path.splitext(url)[1]
if url and end:
# 去除特殊字符
end = re.sub(r'[,。??,/\\·*]', '', end)
# 调用下载函数
download(url, end,fileName+"_"+title)
else:
pass
except Exception as e:
print(e)
pass
if __name__ == '__main__':
targetUrl = '/security/stock/queryCompanyBulletin.do?isPagination=true&productId=&keyWord=&securityType=0101%2C120100%2C020100%2C020200%2C120200&reportType2=&reportType=ALL&beginDate=2020-10-9&endDate=2020-10-9&pageHelp.pageSize=25&pageHelp.pageCount=50&pageHelp.pageNo=1&pageHelp.beginPage=1&pageHelp.cacheSize=1&pageHelp.endPage=5&_=1603242152949'
requests_get(targetUrl)