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": ""}
事实上,它返回给我一个 None 我想获得这部分网站的文本内容:
<div style="font-size:3em; color:#6200C5;">
Orchard</div>
随机词在哪里Orchard
感谢任何类型的帮助
解决方案
不幸的是,在 中没有很多指针BeautifulSoup
,并且您尝试获取的页面非常不适合您的任务(没有 ID、类或其他有用的 html 功能指向)。
因此,您应该更改用于指向 html 元素的方式,并使用 Xpath - 您不能使用BeautifulSoup
. 为此,只需使用html
from 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)
推荐阅读
- macos - NSDocument 应用程序不再能够打开保存的文档
- java - 为视频播放器启动新活动时,如何强制android视频播放器在视频播放后不退出
- java - datagrip 如何从 couchbase 存储桶中获取所有文档?
- python - 无法使用硒单击阴影根元素
- java - 如何更新 TornadoFX 组合框 - Kotlin
- c# - 如何使单元格仅在填充后才能读取?数据网格视图 C#
- wordpress - Wordpress:add_submenu_page() 创建错误
- html - div 拆分窗格,最小宽度
- amazon-web-services - AWS Codebuild - 执行命令时出错:python -m pip install --upgrade --force pip。原因:退出状态1
- javascript - 当用户在提示中输入特定时间时,尝试让此代码显示问候语