Python 如何从HTML页面但从元素本身提取或刮取数据
目前,我使用lxml解析html文档,以从html元素获取数据 但是有一个新的挑战,在HTML元素中有一个数据存储为评级Python 如何从HTML页面但从元素本身提取或刮取数据,python,lxml,Python,Lxml,目前,我使用lxml解析html文档,以从html元素获取数据 但是有一个新的挑战,在HTML元素中有一个数据存储为评级 它很容易提取标签之间的文本,但在标签内没有想法。 你有什么建议 挑战我想摘录“3” 网址: 比尔, 加布里埃尔。试试下面的脚本: from bs4 import BeautifulSoup import requests BASE_URL = "https://webscraper.io/test-sites/e-commerce/allinone/computer
它很容易提取标签之间的文本,但在标签内没有想法。
你有什么建议
挑战我想摘录“3”
网址:
比尔,
加布里埃尔。试试下面的脚本:
from bs4 import BeautifulSoup
import requests
BASE_URL = "https://webscraper.io/test-sites/e-commerce/allinone/computers/laptops"
html = requests.get(BASE_URL).text
soup = BeautifulSoup(html, "html.parser")
for tag in soup.find_all("div", {"class":"ratings"}):
# get all child from the tags
for h in tag.children:
# convert to string data type
s = h.encode('utf-8').decode("utf-8")
# find the tag with data-rating and get text after the keyword
m = re.search('(?<=data-rating=)(.*)', s)
# check if not None
if m:
#print the text after data-rating and remove last char
print(m.group()[:-1])
从bs4导入美化组
导入请求
基本URL=”https://webscraper.io/test-sites/e-commerce/allinone/computers/laptops"
html=请求.get(基本URL).text
soup=BeautifulSoup(html,“html.parser”)
对于soup.find_all(“div”,“class”:“ratings”})中的标记:
#从标记中获取所有子项
对于tag.children中的h:
#转换为字符串数据类型
s=h.编码(“utf-8”).解码(“utf-8”)
#查找具有数据分级的标记,并获取关键字后的文本
m=重新搜索('(?如果我正确理解您的问题和评论,以下内容应提取该页面中的所有评分:
import lxml.html
import requests
BASE_URL = "https://webscraper.io/test-sites/e-commerce/allinone/computers/laptops"
html = requests.get(BASE_URL)
root = lxml.html.fromstring(html.text)
targets = root.xpath('//p[./span[@class]]/@data-rating')
例如:
targets[0]
输出
三,
给我们你的脚本,我们会检查它。谢谢。你能给我一个lxml的例子吗???而不是美丽的汤。因为我已经用lxml和xpath解析元素实现了代码的另一部分。给我看你脚本的一部分,这样我就可以帮你了。我改为soup=BeautifulSoup(html,“lxml”)当然,我会和大家分享,但你们如何在漂亮的汤中使用xpath??
targets[0]