当想要的标签还没有分类时,如何从网站上收集数据?

2024-06-28 19:21:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道如何从网站上获取数据 我找到一个教程,完成了这个

import os
import csv
import requests
from bs4 import BeautifulSoup

requete = requests.get("https://www.palabrasaleatorias.com/mots-aleatoires.php")
page = requete.content
soup = BeautifulSoup(page)

教程告诉我应该使用这样的方法来获取标签的字符串

h1 = soup.find("h1", {"class": "ico-after ico-tutorials"})
print(h1.string)

但是我有一个问题:我想要获取文本内容的标签没有类。。。我该怎么办

我试着把{}放进去,但没用 这也是{"class": ""} 事实上,它给了我一个零 我想获取网站这部分的文本内容:

<div style="font-size:3em; color:#6200C5;">
Orchard</div>

其中Orchard是随机词 谢谢你的帮助


Tags: 文本importdiv内容网站page教程标签
1条回答
网友
1楼 · 发布于 2024-06-28 19:21:40

不幸的是,在BeautifulSoup中没有太多的指针,您试图获取的页面非常不适合您的任务(没有id、类或其他有用的html特性可供指向)

因此,您应该更改指向html元素的方式,并使用Xpath,而不能使用BeautifulSoup。为此,只需使用包lxml中的html来解析页面。下面是一个代码片段(基于this question的答案),它提取了示例中的随机词

import requests
from lxml import html

requete = requests.get("https://www.palabrasaleatorias.com/mots-aleatoires.php")
tree = html.fromstring(requete.content)
rand_w = tree.xpath('/html/body/center/center/table[1]/tr/td/div/text()')
print(rand_w)

相关问题 更多 >