使用请求和lxml进行html刮取,生成<Element x at location>,而不是位于该节点的文本

2024-10-03 17:19:19 发布

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

我正在创建一个Python程序,使用lxml和请求从网站上抓取文本。但是,当我导航到正确的节点时,我的代码会生成一个元素标签,而不是位于该节点的文本

# import packages
from lxml import html
import requests

# initialize program with URL
ficUrl = 'https://www.fanfiction.net/s/10847788/'

# pull metadata
page = requests.get(ficUrl)
tree = html.fromstring(page.content)
title = tree.xpath('//*[@id="profile_top"]/b')
print(title)

当我检查页面时,应该位于该节点的是文本“Goldstein”。但是,我的程序打印[<Element b at 0x11171e548>]。我能做些什么来解决这个问题


Tags: 代码文本import程序tree元素节点title
2条回答

明白了

我需要在xpath的末尾添加一个/text()标记

你可以用beautifulsoup

from bs4 import BeautifulSoup as bs
import requests

r = requests.get('https://www.fanfiction.net/s/10847788/')
soup = bs(r.content, 'lxml')
data = soup.select_one('#profile_top .xcontrast_txt').text
print(data)

相关问题 更多 >