糗事百科实例:
爬取糗事百科段子,假设页面的URL是 http://www.qiushibaike.com/8hr/page/1
python爬虫学习笔记 1.1(通用爬虫和聚焦爬虫)
python爬虫学习笔记 1.2 ( HTTP和HTTPS )
python爬虫学习笔记 1.3 str和bytes的区别
python爬虫学习笔记 1.4 (Request简单使用)request安装
python爬虫学习笔记 1.5 (Requests深入)
python爬虫学习笔记 1.6 (HTTP/HTTPS抓包工具-Fiddler)
python爬虫学习笔记 1.7 (urllib模块的基本使用)
python爬虫学习笔记 1.8 (urllib:get请求和post请求)
python爬虫学习笔记 1.9 (Handler处理器 和 自定义Opener)
python爬虫学习笔记 2 (非结构化数据和结构化数据提取)
python爬虫学习笔记 2.1 (正则表达式re模块)
python爬虫学习笔记 2.2 (使用正则表达式得爬虫得简单案例)
python爬虫学习笔记 2.3 (XPath与lxml类库)
python爬虫学习笔记 2.4 (使用Xpath得案例)
python爬虫学习笔记 2.5 (json与JsonPath)
python爬虫学习笔记 2.6 (糗事百科案例)
python爬虫学习笔记 2.7 (多线程爬虫案例(初步了解))
python爬虫学习笔记 2.8 (beautifulsoup4)
python爬虫学习笔记 2.9 (使用bs4得案例)
python爬虫学习笔记 3 (动态HTML处理和机器图像识别)
python爬虫学习笔记 3.1 (动态HTML介绍)
python爬虫学习笔记 3.2 (Selenium与PhantomJS)
python爬虫学习笔记 3.#(番外) (selenium和chromedriver使用中得问题)
参考代码
#coding=utf-8
import requests
from retrying import retry
from lxml import etree
class Qiubai_spider():
def __init__(self):
self.url = "http://www.qiushibaike.com/8hr/page/{}/"
self.headers = {
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36"
}
@retry(stop_max_attempt_number=5) #调用retry,当assert出错时候,重复请求5次
def parse_url(self,url):
response = requests.get(url,headers=self.headers) #请求url
assert response.status_code==200 #当响应码不是200时候,做断言报错处理
print(url)
return etree.HTML(response.text) #返回etree之后的html
def parse_content(self,html):
item_temp = html.xpath("//div[@class='col1 new-style-col1']")
print(len(item_temp))
for item in item_temp:
#获取用户头像地址
avatar = item.xpath("./div/ul/li[1]/div/div/a/img/@src")[0] if len(item.xpath("./div/ul/li[1]/div/div/a/img/@src"))>0 else None
#为头像地址添加前缀
if avatar is not None and not avatar.startswith("http:"):
avatar = "http:"+avatar
print(avatar)
name = item.xpath("./div/ul/li[2]/div/div/a/span/text()")[0] #获取用户名
print(name)
content = item.xpath("./div[@class='recommend-article']/ul/li[@class='item typs_video']/div[@class='recmd-right']/a[@class='recmd-content']/text()")[0] #获取内容
print(content)
# star_number = item.xpath("./div[@class='recmd-num']/span[1]/text()")[0] #获取点赞数
# print(star_number)
# comment_number = item.xpath("./div[@class='stats']/span[4]/text()")[0] #获取评论数
# print(comment_number)
print("*"*100)
def run(self):
'''函数的主要逻辑实现
'''
url = self.url.format(1) #获取到url
html = self.parse_url(url) #请求url
self.parse_content(html) #解析页面内容并把内容存入内容队列
if __name__ == "__main__":
qiubai = Qiubai_spider()
qiubai.run()