beautifulsoup中find中get_text
时间: 2024-03-18 16:45:29 浏览: 75
在BeautifulSoup中,find()方法用于查找匹配指定标签的第一个子标签,并返回该标签对象。而get_text()方法则用于获取该标签对象的文本内容,即去除HTML标签后的纯文本数据。
举个例子,如果你想获取网页中第一个p标签的文本内容,你可以这样做:
```
from bs4 import BeautifulSoup
import requests
# 发送请求获取网页内容
url = 'http://www.example.com'
response = requests.get(url)
# 将网页内容转换为BeautifulSoup对象
soup = BeautifulSoup(response.text, 'html.parser')
# 查找第一个p标签,并获取其文本内容
p_tag = soup.find('p')
text = p_tag.get_text()
print(text)
```
在这个例子中,我们使用了find()方法查找第一个p标签,并使用get_text()方法获取该标签的文本内容。
相关问题
使用requests和BeautifulSoup库,可使用BeautifulSoup中的find、find_all或select、select_one进行html元素检索
并获取相应信息。
示例:
1. 使用requests库获取网页内容
```python
import requests
response = requests.get('https://www.example.com')
html = response.text
```
2. 使用BeautifulSoup库解析html内容
```python
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
```
3. 使用find或find_all方法查找元素
```python
# 查找第一个h1标签
h1 = soup.find('h1')
# 查找所有p标签
p_list = soup.find_all('p')
```
4. 使用select或select_one方法查找元素
```python
# 查找所有class为example的div标签
div_list = soup.select('.example')
# 查找第一个id为title的h1标签
h1 = soup.select_one('#title')
```
5. 获取元素内容或属性
```python
# 获取h1标签内容
h1_text = h1.text
# 获取p标签中的href属性
p_href = p_list[0].get('href')
```
news_list = soup.find_all("a", class_="news_list_title") for news in news_list: title = news.get_text() link = news.get("href") news_response = requests.get(link) news_soup = BeautifulSoup(news_response.content, "html.parser") content = news_soup.find("div", class_="news_content").get_text() if "公示" in title: ws.append([title, link, content])
这段代码的作用是爬取一个网页中的新闻列表,然后获取每个新闻的标题、链接和内容,并将包含关键词“公示”的新闻信息写入一个 Excel 表格中。具体来说,代码通过 BeautifulSoup 库解析 HTML 页面,获取 class 属性为"news_list_title"的所有a标签,然后遍历每个a标签,获取其标题和链接,随后请求链接,解析新闻详细页面,获取新闻内容,最后判断标题中是否包含关键词“公示”,如果包含,则将新闻的标题、链接和内容写入一个 Excel 表格中。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)