Python 网页解析器BeautifulSoup示例使用

Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式.Beautiful Soup会帮你节省数小时甚至数天的工作时间。

接下来,快事使用一些编程范例,使得尽快熟悉BeautifulSoup使用方法:

# coding:utf8
import re
from bs4 import  BeautifulSoup


html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

soup = BeautifulSoup(html_doc, 'html.parser', from_encoding='utf-8')

print '获取的所有链接'
links = soup.find_all('a')

for link in links:
    print link.name, link['href'], link.get_text()
    
print '获取lacie的链接'
link_node = soup.find('a', href='http://example.com/lacie')
print link_node.name, link_node['href'], link_node.get_text() 

print '正则匹配'
link_node = soup.find('a', href=re.compile(r"ill"))
print link_node.name, link_node['href'], link_node.get_text()

print '获取p段落文字'
p_note = soup.find('p', class_="title")
print p_note.name, p_note.get_text()

    

运行结果:

获取的所有链接
a http://example.com/elsie Elsie
a http://example.com/lacie Lacie
a http://example.com/tillie Tillie
获取lacie的链接
a http://example.com/lacie Lacie
正则匹配
a http://example.com/tillie Tillie
获取p段落文字
p The Dormouse's story


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python网页爬取数据是一种利用Python编程语言的技术,用于从互联网上的网页中提取数据。这项技术对于获取大量数据或自动化数据收集非常有用。 下面是一个简单的Python网页爬取数据示例: 首先,我们需要导入所需的库。在这个示例中,我们将使用Python的requests和BeautifulSoup库。 ```python import requests from bs4 import BeautifulSoup ``` 然后,我们需要指定要爬取的网页链接,并使用requests库发送HTTP请求获取网页内容。 ```python url = "https://example.com" # 替换为要爬取的网页链接 response = requests.get(url) ``` 接下来,我们需要使用BeautifulSoup库将网页内容转换为一个可解析的对象。 ```python soup = BeautifulSoup(response.content, "html.parser") ``` 现在,我们可以使用BeautifulSoup提供的各种方法来查找和提取我们需要的数据。例如,找到网页中的所有超链接。 ```python links = soup.find_all("a") for link in links: print(link.get("href")) ``` 如果我们想要提取网页中的表格数据,我们可以使用BeautifulSoup的find方法和select方法来定位和提取表格元素。 ```python table = soup.find("table") # 如果知道表格的标签名,可以使用find方法 rows = table.select("tr") # 使用select方法可以通过CSS选择器定位表格行 for row in rows: cells = row.find_all("td") for cell in cells: print(cell.text) ``` 最后,我们可以将提取到的数据进行处理、存储或分析,具体取决于我们的需求。 通过使用Python编程语言和相应的库,我们可以快速、灵活地从网页中爬取数据。这个示例只是一个简单的入门,实际的网页爬取任务可能涉及到更多的处理和技巧。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值