python爬取html数据的<i></i>后面的#text怎么爬取
时间: 2023-12-11 22:05:52 浏览: 32
你可以使用BeautifulSoup库来解析HTML文档,并通过选择器来定位目标元素。在选择器中,#text可以表示HTML元素的文本内容。如果你想要获取<i></i>标签后面紧跟的文本内容,可以通过如下代码实现:
```python
from bs4 import BeautifulSoup
import requests
html = requests.get('http://example.com').text
soup = BeautifulSoup(html, 'html.parser')
i_tag = soup.find('i')
text = i_tag.next_sibling.strip()
print(text)
```
这里使用了`next_sibling`方法来获取`<i></i>`标签后面的兄弟节点(即文本节点),再通过`strip()`方法去除空白字符。你可以将代码中的'http://example.com'替换为你要爬取的网页地址。
相关问题
爬取页面中<div class="x_z d_q on"><ul><li></li></ul><div class="g_d"><span class="z_k">展开</span><span class="s_q">收起</span></div></div> 里面的li
你可以使用Python的requests和BeautifulSoup库来爬取页面并提取所需的信息。以下是一个基本的示例代码:
```python
import requests
from bs4 import BeautifulSoup
# 发送请求获取页面内容
url = 'http://example.com'
response = requests.get(url)
# 解析页面内容
soup = BeautifulSoup(response.text, 'html.parser')
li_list = soup.select('div.x_z.d_q.on li')
# 打印提取的信息
for li in li_list:
print(li.text)
```
在这个示例中,我们首先发送了一个GET请求来获取页面的内容,并将其传递给BeautifulSoup对象进行解析。我们使用select方法来选择所需的li元素。最后,我们遍历所有选定的li元素并打印其文本内容。
python 爬虫爬取 <br>便签后 无标签包裹的文字
在 Python 中,可以使用第三方库 `beautifulsoup4` 来解析 HTML 页面,获取其中的文本内容。具体来说,可以使用 `BeautifulSoup` 类的 `get_text()` 方法来获取页面中的纯文本内容。
以下是一个示例代码,假设需要爬取一个页面中的 `<br>` 标签后的无标签包裹的文字:
```python
import requests
from bs4 import BeautifulSoup
# 发送 GET 请求获取页面内容
response = requests.get('https://example.com/page')
# 解析页面内容,获取所有 <br> 标签后的文本
soup = BeautifulSoup(response.text, 'html.parser')
br_tags = soup.find_all('br')
for br_tag in br_tags:
next_node = br_tag.next_sibling
while next_node is not None and next_node.name == 'br':
next_node = next_node.next_sibling
if next_node is not None:
print(next_node.get_text())
```
以上代码中,首先使用 `requests.get()` 方法发送 GET 请求,获取页面内容。接着使用 `BeautifulSoup` 类将页面内容进行解析,并使用 `find_all()` 方法获取所有的 `<br>` 标签。然后对于每个 `<br>` 标签,使用 `next_sibling` 属性获取其下一个兄弟节点,判断节点是否为 `<br>` 标签,如果是则继续获取其下一个兄弟节点,直到遇到一个非 `<br>` 标签的节点。最后使用 `get_text()` 方法获取该节点的纯文本内容。