参考 string headers esp window com -c -s
爬取糗事百科段子,假设页面的 URL 是 http://www.qiushibaike.com/8hr/page/1
、
- 用户头像链接
、
- 用户姓名
、
- 段子内容
和
- 点赞次数
- 评论次数
- #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]/* */)[0].encode('utf-8')
- username = site.xpath([email protected]/* */)[0].encode('utf-8')
- #username = site.xpath('.//h2')[0].text
- content = site.xpath('.//div[@class="content"]/span')[0].text.strip().encode('utf-8')
- # 投票次数
- vote = site.xpath('.//i')[0].text
- #print site.xpath('.//*[@class="number"]')[0].text
- # 评论信息
- comments = site.xpath('.//i')[1].text
- print imgUrl, username, content, vote, comments
- except Exception, e:
- print e
python 糗事百科实例
来源: http://www.bubuko.com/infodetail-2274212.html