一、利用python爬取上市公司办公地址
IDLE编辑器,python3.8版本。
import requests
from bs4 import BeautifulSoup
import re
import xlwt
def getHTMLText(url, code=“utf-8”):
kv={‘user-agent’:‘Mozilla/5.0’}
try:
r = requests.get(url,headers=kv)
r.raise_for_status()#抛出异常
r.encoding =r.apparent_encoding#设定编码格式
return r.text
except:
return “”
def getStockList(lst, stockURL):
html = getHTMLText(stockURL, “gb2312”) #只获取htlm文本
soup = BeautifulSoup(html, ‘html.parser’) #html解析,到这里把整个网站源代码排版整理干净
a = soup.find_all(‘a’) #解析页面,找到所有的a标签
for i in a:
try:
#找到a标签中的href属性,并且判断属性中间的链接,把链接后面的数字取出来
href = i.attrs[‘href’]
#深圳交易所的代码以sz开头,上海交易所的代码以sh开头,股票的数字有6位构成,所以正则表达式可以写为[s][hz]\d{6}
lst.append(re.findall(r"[s][hz][0,3,6][0-9]{5}", href)[0])
except:
continue
def getStockInfo(lst, stockURL):
count = 0
for stock in lst[3500:3814]:
url = stockURL + ‘s’+ stock[2:8] + “.shtml”
#print(url)
inflinshi=[]
html = getHTMLText(url)#对一只股票进行操作
soup = BeautifulSoup(html, ‘html.parser’)
tds = soup.find_all(‘td’,attrs={‘class’: ‘’})
#print(tds[15].string)
count = count + 1
sheet01.write(count+1,0,tds[0].string)
sheet01.write(count+1,1,tds[1].string)