学会python语法后的第一个爬虫
---恢复内容开始---
#-*_coding:utf8-*- import requests from lxml import etree url='http://quotes.toscrape.com/page/qwe/' for i in range(1,100): num=str(i) url_n=url.replace('qwe',num) response=requests.get(url_n) r_decode=response.content.decode('utf-8') r_html=etree.HTML(r_decode) quote=r_html.xpath('/html/body/div/div[2]/div[1]/div/span[1]/text()') print(quote)
话不多说,这是我在查阅了各种博客和各种百度之后写出的比较精简的一个爬虫,爬取内容也很简单
功能是爬取网站http://quotes.toscrape.com/中的quote

代码详解
url='http://quotes.toscrape.com/page/qwe/'
得到具体需要爬取内容的url地址,‘qwe’用来标记页码的位置,用于字符串替换,可以一用其他与原网页不冲突的任何字符串标记,建议不要太长,以后也许有更好的办法来标记
for i in range(1,100): num=str(i) url_n=url.replace('qwe',num) response=requests.get(url_n) r_decode=response.content.decode('utf-8') r_html=etree.HTML(r_decode) quote=r_html.xpath('/html/body/div/div[2]/div[1]/div/span[1]/text()') print(quote)
提取前100页的quote
用requests.get()函数来获取url的response类,并对内容进行decode解码,再用etree.HTML()对内容进行处理,使之可以被xpath函数解析

检查页面元素,找到quote文本的位置,右键复制xpath路径,得到:/html/body/div/div[2]/div[1]/div[3]/span[1]/text()
一个页面有多个需要截取的quote,在这里将路径修改一下,得到:/html/body/div/div[2]/div[1]/div/span[1]/text(),得到可以取得以该页面截取quote为元素的一个list
打印得:

可能会有数据的后续处理,有机会再写
---恢复内容结束---

浙公网安备 33010602011771号