1环境:pycharm,python3.4
2.源码解析
import requests
import re
from bs4 import BeautifulSoup#通过requests.get获取整个网页的数据
def getHtmlText(url):try:
r = requests.get(url)
# to cheack r.status_code is your expected
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return "craw failed"
#下图是网页中的内容:
#解析页面内容,通过find_all函数find所有的a标签的内容,返回一个list,
然后通过正则表达式匹配re.findall(r"[s][zh]\d{6}", href,得到href中的诸如sh201002或者sz201001这样的号码;将所有得号码赋给一个list保存
def getHtmlList(lst, list_url):
html = getHtmlText(list_url)soup = BeautifulSoup(html, "html.parser")
a = soup.find_all('a')
for i in a:
try:
href = i.attrs['href']
lst.append(re.findall(r"[s][zh]\d{6}", href)[0])
except:
continue
print("lst:", lst)
#下面函数作用:通过上一个函数得到的号码,传给这个函数,拼成另一个url,获取这个url网页中的数据
抓取过程同理;不同之处是这里通过soup.find("div", attrs={'class': 'stock-bets'})即:find函数抓取所有div标签,属性是stock-bets的内容,),find只返回第一个符合条件的结果,所以soup.find()后面可以直接接.text或者get_text()来获得标签中的文本;find_all()得到的所有符合条件的结果和soup.select()一样都是列表list
def getHtmlInfo(lst, info_url, fpath):for l in lst:
info_url = info_url + l + ".html"
html = getHtmlText(info_url)
try:
if html == "":
continue
soup = BeautifulSoup(html, "html.parser")
betsInfo = soup.find("div", attrs={'class': 'stock-bets'})
infoDict = {}
name = betsInfo.find_all(attrs={'class': 'bets-name'})[0]
infoDict.update({"name": name.text.split()[0]})
#进一步得到标签是dd和dt的所有数据,所以这里用的find_all,返回一个list,这里dd是key值,dt可看成value值,存入字典
keylist = betsInfo.find_all("dd")
keyvalue = betsInfo.find_all("dt")
for i in range(len(keylist)):
try:
key = keylist[i].text
val = keyvalue[i].text
dict2 = {'key': 'val'}
infoDict.update(dict2)
# infoDict[key] = val
except:
print("error")
#将我们要的数据写入文件
with open(fpath, 'a', encoding='utf-8') as f:f.write(str(infoDict) + '\n')
except:
continue
#主函数,调用上面的抓取网页的函数即可
def main():
list_url = "http://quote.eastmoney.com/stocklist.html"
info_url = "https://gupiao.baidu.com/stock/"
output_file = './stockInfo.txt'
slist = []
getHtmlList(slist, list_url)
getHtmlInfo(slist, info_url, output_file)
main()