繁体   English   中英

如何从html属性中获取文本

[英]How to get text from html attributes

我试图解析一个页面以获取一些元素作为文本,但我找不到如何从选择中获取文本

例如,下面的 html 有 data-initial-rating="4" 和 title="Members who rating this thread">12 Votes",但我不明白

<select name="rating" class="br-select input" data-xf-init="rating" data-initial-rating="4" data-rating-href="/threads/isis-the-fall-v1-02-tjord.117157/br-rate" data-readonly="false" data-deselectable="false" data-show-selected="true" data-widget-class="bratr-rating" data-vote-content="<div data-href=&quot;/threads/game-mod-v-1-02/br-user-rated&quot; data-xf-click=&quot;overlay&quot; data-xf-init=&quot;tooltip&quot; title=&quot;Members who rated this thread&quot;>12 Votes</div>" style="display: none;">
                <option value="">&nbsp;</option>
<option value="1">Terrible</option>
<option value="2">Poor</option>
<option value="3">Average</option>
<option value="4">Good</option>
<option value="5">Excellent</option>

            </select>

我试过的

import requests
import lxml.html


response = requests.get('somewebsite.com')
tree = lxml.html.fromstring(response.text)
# full xptah
messy_rating_and_votes = tree.xpath('/html/body/div[2]/div/div[3]/div/div[1]/div/div/div[3]/div/div[2]/div/div/select')
print(messy_rating_and_votes) # its just print empty list, so i cant use .text or .text_content()

所以,我想那是我选择错误或使用错误的方法,但近 2 小时的谷歌搜索对我有帮助

这个例子使用 BeautifulSoup4

import requests
from bs4 import BeautifulSoup

response = requests.get("somewebsite.com")
soup = BeautifulSoup(response.content, 'html5lib')  # requires pip install html5lib

for option in soup.find_all('option'):
    print(f"value: {option['value']} text: {option.text}")

我们无法判断您的 XPath 的正确性,因为您没有包含完整的文档。 例如,您可能在该路径的任何地方都犯了一个小错误,例如div[3]应该是div[2]

您可以尝试使用descendant轴(带有语法快捷方式// )而不是默认child轴的更简单的路径。 这将使您能够跳过文档的许多杂乱结构。 例如

//select[@name='rating']

或者

//select[@name='rating'][@data-xf-init='rating']

...或者无论您需要多么具体地识别该特定的select元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM