爬虫之旅游网
案例
import requests
from bs4 import BeautifulSoup
url='http://www.cntour.cn/'
strhtml=requests.get(url)
#print(strhtml.text)
soup=BeautifulSoup(strhtml.text,'lxml')
data=soup.select("#main > div > div.mtop.firstMod.clearfix > div.centerBox > ul.newsList > li.top > a")
data
运行结果如下:
#清洗和组织数据
#正则中\d表示一个数字,\d+表示多个数字
import re
for item in data:
result={
'title':item.get_text(),
'link':item.get('href'),
'ID':re.findall(r'\d+',item.get('href'))
}
print(result)
运行结果如下:
关于match,search,findall的匹配区别
#match当且仅当匹配的字符串开头,才能匹配到
import re
print(re.match("c","abcde"))
print(re.match("a","abcde"))
pattern=re.compile('c')
print(pattern.match('abcdef',2))
运行结果如下:
print(re.search("c","abcde"))
运行结果如下:
findall结果如下: