根据
嵩老师的爬虫课程,写出来了对于股票的爬取,然而由于种种原因,程序各种BUG,开始以为是自己写错了,调试了很久才发现是其他原因,最坑的一个问题是百度股票网站可以访问,但是如果你用cmd去ping这个网址,会发现找不到服务器,试了许久,最后把我DNS地址改成8.8.8.8成功解决了这个问题,但是运行起来速度好慢,两个小时才爬了两千多股票,下面是程序代码
import traceback
import requests
import re
from bs4 import *
import bs4
fpath = 'E://a.txt'
rx = requests.get('https://gupiao.baidu.com/stock/sh000001.html')
rx.encoding = 'utf-8'
html = rx.text
try:
infodick = {}
soup = BeautifulSoup(html,'html.parser')
print(soup)
stockinfo = soup.find('div',attrs={'class':'stock-bets'})
name = stockinfo.find_all(attrs={'class':'bet-name'})[0]
infodick.update({'股票名称':name.text.split()[0]})
keylist = stockinfo.find_all('dt')
valuelist = stockinfo.find_all('dd')
for i in range(len(keylist)):
key = keylist[i].text
val = valuelist[i].text
infodick[key] = val
print(infodick[i])
with open(fpath,'w',encoding='utf-8')as f:
f.write(str(infodick)+ '\n')
f.close()
print('success')
except:
traceback.print_exc()
print('failed')
![](https://i-blog.csdnimg.cn/blog_migrate/7e7062d4cf6d145b1d0f636b038e2c03.png)