首页 > 解决方案 > 当想要的标签没有分类时如何从网站收集数据?

问题描述

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

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": ""} 事实上,它返回给我一个 None 我想获得这部分网站的文本内容:

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

随机词在哪里Orchard感谢任何类型的帮助

标签: python

解决方案


不幸的是,在 中没有很多指针BeautifulSoup,并且您尝试获取的页面非常不适合您的任务(没有 ID、类或其他有用的 html 功能指向)。

因此,您应该更改用于指向 html 元素的方式,并使用 Xpath - 您不能使用BeautifulSoup. 为此,只需使用htmlfrom packagelxml来解析页面。在您的示例中提取随机单词的代码片段下方(基于此问题的答案)。

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)

推荐阅读