python中解析网页内容基本步骤
- 使用BeautifulSoup解析网页
Soup = BeautifulSoup(html, 'lxml')
- 描述要爬取得东西在哪里
=Soup.select(‘路径’)
- 从标签中获得需要的信息,按一定格式装在数据容器中(字典的列表),便于查询
<p>
Something</p>
[{title=Something, rate=4.0},{title=Something, rate=4.0},{title=Something, rate=4.0},{title=Something, rate=4.0}]
两种不同的路径描述方式
- CSS Selector:
例如:body>div.main-content>ul>li:nth-child(1)>img
- XPATH
例如:/html/body/div[2]/ul/li(1)/img
作业代码
from bs4 import BeautifulSoup
info= []
#读取本地HTML文件并找到要爬取的片段
with open('E:/工作盘Workshop/a3-编程练习/Python Practice/0824/1.2/index.html','r',) as web_data:
Soup = BeautifulSoup(web_data,'lxml')
images = Soup.select('body > div:nth-of-type(1)> div > div.col-md-9 > div:nth-of-type(2) > div > div > img')
titles = Soup.select('body > div:nth-of-type(1) > div > div.col-md-9 > div:nth-of-type(2) > div > div > div.caption > h4 > a')
prices = Soup.select('body > div:nth-of-type(1) > div > div.col-md-9 > div:nth-of-type(2) > div > div > div.caption > h4.pull-right')
votes = Soup.select('body > div:nth-of-type(1) > div > div.col-md-9 > div:nth-of-type(2) > div > div > div.ratings > p.pull-right')
stars = Soup.select('body > div:nth-of-type(1) > div > div.col-md-9 > div:nth-of-type(2) > div > div > div.ratings > p:nth-of-type(2)')
#print(images,titles,prices,votes,stars,sep='\n------------------\n')
#从片段中提取有效数据,每组数据生成一个字典,再把字典放入列表
for title,image,price,vote,star in zip(titles,images,prices,votes,stars):
data = {
'title':title.get_text(),
'price':price.get_text(),
'star': len(star.find_all("span", "glyphicon glyphicon-star")),
'vote':vote.get_text()[:-8],
'image':image.get('src')
}
info.append(data)
#因列表较长,用一个函数逐条打印各元素
def print_lol(the_list):
for each_item in the_list:
print(each_item)
print_lol(info)
输出效果
遗留问题
- Chrome浏览器中copy selector得到的路径中有一处错误,手工更正后才能找到元素。元素实际位置是
body > div:nth-of-type(1)
下面,浏览器复制出来的路径却是body > div:nth-of-type(2)
。
- 能否找到更高效的方法把-child替换为-of-type,手工修改确实很浪费时间。