Python 爬虫 xpath 和 bs4

Catalog

xpath

lxml模块中的xpath

html = '''<body>
<p class="a">A</p>
<p class="b">
<a href="https://blog.youkuaiyun.com/Yellow_python">B</a>
</p>
</body>'''
from lxml import etree
# 创建【Element】对象
element = etree.HTML(html, etree.HTMLParser())
# xpath 提取信息,返回列表
text = element.xpath('//body/p[1]/text()')
print(text)
href = element.xpath('//body/p/a/@href')
print(href)
打印结果
[‘A’]
[‘ https://blog.youkuaiyun.com/Yellow_python‘]

scrapy中的xpath

  1. 运行终端
  2. scrapy shell https://blog.youkuaiyun.com/Yellow_python
  3. response.xpath(”).extract()

response.xpath(‘/html/body/header/div/div[1]/h2/a/text()’).extract_first()
‘Yellow_python的博客’

BeautifulSoup

html = '''<body>
<p class="a">A</p>
<p class="b">
<a href="https://blog.youkuaiyun.com/Yellow_python">B</a>
</p>
</body>'''
from bs4 import BeautifulSoup
# 创建 bs 对象
bs = BeautifulSoup(html, 'html.parser')
# 提取信息
first = bs.find('a')
# 查找第1个
print(first)
print(type(first))  # <class 'bs4.element.Tag'>
print(first.get_text())
# 查找全部,返回列表
all = bs.find_all('p', {'class': 'a'})
print(all)
print(type(all))  # <class 'bs4.element.ResultSet'>
# 转字符串
prettify = bs.prettify()
print(prettify)
print(type(prettify))  # <class 'str'>
Python爬虫中的bs4xpath是两种常用的数据提取工具。 bs4(Beautiful Soup 4)是一个基于Python的库,用于解析HTMLXML文档。它能够帮助我们从网页中提取数据并进行处理。bs4提供了一些简单且易于使用的方法,例如通过标签名、类名、属性等进行查找筛选数据。 下面是一个简单的使用bs4进行数据提取的例子: ```python from bs4 import BeautifulSoup import requests # 发送HTTP请求获取页面内容 url = "http://example.com" response = requests.get(url) html_content = response.content # 使用bs4解析页面内容 soup = BeautifulSoup(html_content, 'html.parser') # 提取数据 title = soup.title.text print("网页标题:", title) # 查找某个标签并获取其文本内容 h1 = soup.find("h1") print("h1标签内容:", h1.text) # 查找所有的链接并输出链接文本URL links = soup.find_all("a") for link in links: print("链接文本:", link.text) print("链接URL:", link["href"]) ``` 另一方面,XPath是一种用于选择XML文档中节点的语言。在爬虫中,我们可以使用XPath来从HTML或XML文档中提取数据。XPath提供了强大且灵活的选择器,可以使用路径表达式来定位节点。 下面是一个使用XPath进行数据提取的示例: ```python import requests from lxml import etree # 发送HTTP请求获取页面内容 url = "http://example.com" response = requests.get(url) html_content = response.content # 使用lxml解析页面内容 tree = etree.HTML(html_content) # 提取数据 title = tree.xpath("//title/text()")[0] print("网页标题:", title) # 查找某个标签并获取其文本内容 h1 = tree.xpath("//h1/text()")[0] print("h1标签内容:", h1) # 查找所有的链接并输出链接文本URL links = tree.xpath("//a") for link in links: link_text = link.xpath("text()")[0] link_url = link.xpath("@href")[0] print("链接文本:", link_text) print("链接URL:", link_url) ``` 以上就是使用bs4XPath进行数据提取的示例代码。希望能帮助到你!如有需要,请随时追问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小基基o_O

您的鼓励是我创作的巨大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值