python中如何使用XPath爬取小说

360次阅读
没有评论

python中如何使用XPath爬取小说

1、说明

xpath是一种在XML文档中搜索信息的语言。

2、过程

获得浏览器中的标题和作者测试。

在谷歌安装xpath插件:

在html中找到book-mid-info:

找到我们想得到小说的名字、作者

即//div[@class='book-mid-info']/h4/a/txt()

3、实例

# 作者:
# 开发时间:2021/4/8/0008 8:24
 
import requests
from lxml import etree
url="https://www.qidian.com/rank/yuepiao"
headers={'user-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3861.400 QQBrowser/10.7.4313.400'}
#发送请求
resp=requests.get(url,headers)
e=etree.HTML(resp.text) #类型转换,把str转变为class 'lxml.etree._ELement
print(type(e))
names=e.xpath('//div[@class="book-mid-info"]/h4/a/text()')
authors=e.xpath('//p[@class="author"]/a[1]/text()')
print(names)
print(authors)
#名称和作者对应
for name,authors in zip(names,authors):
    print(name,":",authors)
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-04-26发表,共计803字。
新手QQ群:570568346,欢迎进群讨论 Python51学习