可以理解为:编译之前只是符合语法的单一字符串,编译后才是符合特征的正则表达式
因此,当正则表达式中包含转义符时,使用raw string类型来表示正则表达式
由于match是从第一个字符开始匹配,第一个字符为B,不符合正则表达式,因此返回的match对象没有group值,因此需要判断
替换符合正则表达式的字符串
对一个正则表达式在多个函数中的使用:compile
regex才是正则表达式对象,可以使用对象方法,与re库的6个方法一致
函数去掉第一个参数(正则表达式字符串)
一个字符串中可以有多个匹配项:
re库默认贪婪匹配
如何使用最小匹配?加一个问号
查看网页源代码可知,淘宝界面价格对应view_price
商品名称对应raw_title
import requests
import re
def getHTMLText(url):
try:
r=requests.get(url,timeout=30)
r.raise_for_status()
r.encoding=r.apparent_encoding
return r.text
except:
return ""
def parsePage(lit,html):
try:
plt=re.findall(r'\"view_price\"\:\"[\d\.]*\"',html)
tlt=re.findall(r'\"raw_title\"\:\".*?\"',html)
for i in range(len(plt)):
price=eval(plt[i].split(':')[1])
title=eval(tit[i].split(':')[1])
ilt.append([price,title])
except:
print("")
def printGoodList(ilt):
tplt="{:4}\t{:8}\t{:16}"
print(tplt.format("序号","价格","商品名称"))
count=0
for g in ilt:
count=count+1
print(tplt.format(count,g[0],g[1]))
def main():
goods='书包'
depth=3
start_url='https://s.taobao.com/search?q='+goods
infoList=[]
for i in range(depth):
try:
url=start_url+'&s='+str(44*i)
html=getHTMLText(url)
parsePage(infoList,html)
except:
continue
printGoodList(infoList)
main()
实测已经打印不出来了,应该是界面有改版,个人没有前端知识,就不debug了
当前技术路线,需要我们选取将数据写在html页面中的网站
而实例中给出的获取股票列表的网站:
http://quote.eastmoney.com/stocklist.html
现在查看源代码已经获取不到内容,也就不是吧数据写在html中
而获取股票详情的页面http://gupiao.baidu.com/stock/
甚至已经不存在了
因此这个例子2021.2也不可实现QAQ
以下代码仅供参考思路
import requests
from bs4 import BeautifulSoup
import traceback
import re
def getHTMLText(url):
try:
r=requests.get(url,timeout=30)
r.raise_for_status()
r.encoding=r.apparent_encoding#这里如果是定向爬虫可以写死,不要动态分析,节省时间
return r.text
except:
return ""
def getStockList(lst,stockURL):
html=getHTMLText(stockURL)
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][hz]\d{6}",href)[0])
except:
continue
def getStockInfo(lst,stockURL,fpath):
for stock in lst:
url=stockURL+stock+".html"
html=getHTMLText(url)
try:
if html=="":
continue
infoDict={
}
soup=BeautifulSoup(html,'html.parser')
stockInfo=soup.find('div',attrs={
'class':'stock-bets'})
name=stockInfo.find_all(attrs{
'class':'bets-name'})[0]
infoDict.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
infoDict[key]=val
with open(fpath,'a',encoding='utf-8') as f:
f.write(str(infoDict)+'\n')
except:
traceback.print_exc()#打印错误信息
continue
def main():
stock_list_url='http://quote.eastmoney.com/stocklist.html'
stock_info_url='http://gupiao.baidu.com/stock/'
output_file='D://BaiduStockInfo.txt'
slist=[]
getStockList(slist,stock_list_url)
getStockInfo(slist,stock_info_url,output_file)
main()
\r能够将打印的光标移动到头部,下一次打印就会覆盖上一次打印,实现不换行的进度信息展示
idle中禁止了\r的使用,可以在命令行中实现