b站【Python网络爬虫与信息提取】.MOOC. 北京理工大学 p46-48 示例
import requests
from bs4 import BeautifulSoup
import bs4
import re
import traceback
import lxml
import random
import fakeip
proxies = {}
headers = {
'authority': 's.taobao.com',
'cache-control': 'max-age=0',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Safari/537.36',
'sec-fetch-dest': 'document',
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'sec-fetch-site': 'same-site',
'sec-fetch-mode': 'navigate',
'sec-fetch-user': '?1',
'referer': '*',
'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
'cookie': '*',
}
def getHTMLText(url, code='utf-8'):
try:
r = requests.get(url, timeout=2, headers=headers)
print(r.request.url)
r.raise_for_status()
r.encoding = code
return r.text
except:
print("getHTMLText Error")
traceback.print_exc()
def getStockList(lst, stockListURL):
html = getHTMLText(stockListURL, 'GB2312')
soup = BeautifulSoup(html, 'html.parser')
a = soup.find_all('a')
for i in a:
try:
href = i.attrs['href']
stockNum = re.findall(r"\d{6}", href)[0]
lst.append(stockNum)
except:
continue
def getStockInfo(lst, stockInfoURL, fpath):
count = 0
summary_list = []
for stock in lst[-1:-50:-1]:
url = stockInfoURL + stock
html = getHTMLText(url, 'GB2312')
print(stock)
try:
if html == "":
continue
soup = BeautifulSoup(html, 'html.parser')
name = (soup.find(name='p', attrs={'class': 'fz24'})).string
price = soup.find(name='td', attrs={'class':'tl'}).find_next_sibling(name='td').string
summary_list.append([stock, name, price])
print([stock, name, price])
count = count + 1
print('\r当前进度:{:.2f}%'.format(count*100/len(lst)),end='')
except:
count = count + 1
print('\r当前进度:{:.2f}%'.format(count * 100 / len(lst)), end='')
continue
try:
with open(fpath, 'a', encoding='utf-8') as f:
for i in summary_list:
for j in range(3):
f.write(str(i[j]) + " ")
f.write('\n')
except:
traceback.print_exc()
print("Failed to open file!")
def main():
stock_list_url = 'http://quote.eastmoney.com/stock_list.html'
stock_info_url = 'http://data.10jqka.com.cn/market/lhbgg/code/'
output_file_path = 'E://stock.txt'
stocklist = []
getStockList(stocklist, stock_list_url)
getStockInfo(stocklist, stock_info_url, output_file_path)
main()