[英]How to get all attributes of section of text from a html string in Python?
[英]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="/threads/game-mod-v-1-02/br-user-rated" data-xf-click="overlay" data-xf-init="tooltip" title="Members who rated this thread">12 Votes</div>" style="display: none;">
<option value=""> </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.