python beautifulsoup4 findall 之后获取 href
时间: 2024-05-01 08:17:57 浏览: 7
可以使用以下代码来获取 href:
```python
from bs4 import BeautifulSoup
import requests
# 发送请求获取网页内容
response = requests.get(url)
content = response.content
# 使用BeautifulSoup解析网页内容
soup = BeautifulSoup(content, 'html.parser')
# 查找包含href的标签
links = soup.findAll('a')
# 循环遍历标签获取href
for link in links:
href = link.get('href')
print(href)
```
需要将 `url` 替换为你要获取 href 的网页地址。在上述代码中,我们首先发送请求来获取网页内容,然后使用 BeautifulSoup 库对网页内容进行解析。接着查找所有包含 href 属性的标签,并使用循环遍历每个标签,获取并输出 href。
相关问题
python bs4.BeautifulSoup.find_all函数用法
`find_all()` 函数是 BeautifulSoup 库中的函数,用于在 HTML 或 XML 文档中查找所有匹配给定标签的元素。该函数接受一个参数,即要查找的标签名,并返回一个包含所有匹配元素的列表。
用法:
```
soup.find_all(name, attrs, recursive, string, limit, **kwargs)
```
其中:
- name: 可以是标签名,字符串,正则表达式,列表
- attrs: 可以是字典,字符串
- recursive: 递归查找,默认True
- string: 查找文本
- limit: 限制查找数量
示例:
```
from bs4 import BeautifulSoup
html = """
<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>
</body>
</html>
"""
soup = BeautifulSoup(html,'lxml')
soup.find_all('a')
#结果是返回所有的<a>标签
```
Python Beautifulsoup4的使用例子
好的,下面是一个更具体的使用例子:
假设我们要从一个网页中获取所有的新闻标题和对应的链接。我们可以先使用Requests库获取网页内容,然后使用Beautifulsoup4进行解析和查找。例如,我们要获取新浪新闻首页的标题和链接,可以使用以下代码:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://www.sina.com.cn/'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
html = requests.get(url, headers=headers).text
soup = BeautifulSoup(html, 'html.parser')
news_list = soup.find_all('a', class_='news-item')
for news in news_list:
title = news.get_text()
link = news['href']
print(title, link)
```
以上代码中,我们首先定义了要获取的网页的URL和请求头部。然后,使用Requests库发送请求,获取网页内容。接着,使用Beautifulsoup4将网页内容解析成一个BeautifulSoup对象。然后,使用`find_all`方法查找所有class属性为`news-item`的`a`标签,这些标签包含了新闻标题和链接。最后,遍历所有的标签,获取标题和链接,并输出。
输出结果如下:
```
新浪首页 https://www.sina.com.cn/
新闻 http://news.sina.com.cn/
财经 http://finance.sina.com.cn/
娱乐 http://ent.sina.com.cn/
体育 http://sports.sina.com.cn/
```
以上代码只是一个简单的例子,实际中可能需要对网页结构进行更深入的分析和查找。Beautifulsoup4提供了丰富的方法和属性,可以根据具体需求进行使用。