鸠兹古镇贴吧页面标题、链接及翻页爬取。
1、导入第三方库
import requests
from lxml import etree
2、爬取思路
url----headers----发送请求,获取响应------从响应中提取数据(数据和翻页用的url)-------终结条件
3、url、headers
self.url = 'https://tieba.baidu.com/f?kw=%F0%AF%D7%C8%B9%C5%D5%F2&fr=ala0&tpl=5'.format(name)
self.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Edg/94.0.992.38"
}
4、发送请求,获取响应
response = requests.get(url,headers=self.headers)
with open("temp.html","wb") as f:
f.write(response.content)
return response.content
5、提取数据
把html源码转化成Element对象。
利用etree.HTML,将html字符串(bytes类型或str类型)转化为Element对象,Element对象具有xpath的方法,返回结果的列表。
一个标题为一个分组。
ps:如果选取内容中含有广告,则加一个所需内容共有标签。
html = etree.HTML(data)
el_list = html.xpath('//*[@id="thread_list"]/li[@class=" j_thread_list clearfix thread_item_box"]/div/div[2]/div[1]/div[1]/a')
!未获取到数据
绿色的内容,被注释掉。浏览器功能强大。
浏览器显示的原因:浏览器有引擎,可以显示。
解决:换一个低端浏览器请求头或进行如下方法:
data = data.decode().replace("<!--","").replace("-->","")
data_list = []
for el in el_list:
temp={}
temp['title'] = el.xpath("./text()")[0]
temp['link'] = 'https://tieba.baidu.com' + el.xpath("./@href")[0]
data_list.append(temp)
获得标题和链接 。
获取下一页:
next_url = 'https:'+html.xpath('//*[@id="frs_list_pager"]/a[4]/@href')[0]
6、终结条件
if next_url==None:
break