python 糗事百科實例
爬取糗事百科段子,假設頁面的URL是 http://www.qiushibaike.com/8hr/page/1
要求:
-
使用requests獲取頁面信息,用XPath / re 做數據提取
-
獲取每個帖子裏的
用戶頭像鏈接
、用戶姓名
、段子內容
、點贊次數
和評論次數
-
保存到 json 文件內
參考代碼
#qiushibaike.py
#import urllib
#import re
#import chardet
import requests
from lxml import etree
page = 1
url = ‘http://www.qiushibaike.com/8hr/page/‘ + str(page)
headers = {
‘User-Agent‘: ‘Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36‘,
‘Accept-Language‘: ‘zh-CN,zh;q=0.8‘}
try:
response = requests.get(url, headers=headers)
resHtml = response.text
html = etree.HTML(resHtml)
result = html.xpath(‘//div[contains(@id,"qiushi_tag")]‘)
for site in result:
item = {}
imgUrl = site.xpath([email protected]
python 糗事百科實例