python爬虫-网页数据提取

python 复制代码
import requests
#headers = 网页右键->Network->最下面的User-Agent复制。
headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"}
#你想要的网址
url = "https://www.xinpianchang.com/discover/article?from=navigator"
response = requests.get(url, headers=headers)
print(response)# 打印200 说明访问成功
#下面是正式的数据提取,构建xpath的对象
from lxml import etree
tree = etree.HTML(response.text)#页面的元素树
##示例1 标题
elements = tree.xpath('//h2[@class="truncate block"]')#在Elements寻找你想要的元素,可以在页面移动#光标
for element in elements:
    print(element.text)
##也可以在elements中右键copy xpath,这里需要分析一下,将复制的xpath删除一部分
print(tree.xpath('//*[@id="__next"]/section/main/div/div/div/div/div/a/div/ul/li[1]/span[2]')[0].text)
print(tree.xpath('//*[@id="__next"]/section/main/div/div/div/div/div/a/div/ul/li[2]/span[2]')[0].text)
print(tree.xpath('/html/body/div/section/main/div/div/div/div/div/div/a/h2')[1].text)
  


相关推荐
二哈喇子!1 小时前
BOM模型
开发语言·前端·javascript·bom
二哈喇子!1 小时前
空指针异常
开发语言
咚为1 小时前
Rust Print 终极指南:从底层原理到全场景实战
开发语言·后端·rust
jaray1 小时前
PyCharm 2024.3.2 Professional 如何更换 PyPI 镜像源
ide·python·pycharm·pypi 镜像源
%xiao Q1 小时前
GESP C++五级-202406
android·开发语言·c++
Psycho_MrZhang1 小时前
Neo4j Python SDK手册
开发语言·python·neo4j
Traced back2 小时前
# C# + SQL Server 实现自动清理功能的完整方案:按数量与按日期双模式
开发语言·c#
sin22012 小时前
MyBatis的执行流程
java·开发语言·mybatis
web3.08889992 小时前
1688图片搜索API,相似商品精准推荐
开发语言·python
二哈喇子!2 小时前
JAVA环境变量配置步骤及测试(JDK的下载 & 安装 & 环境配置教程)
java·开发语言