簡體   English   中英

如何使用 LXML 將路徑中的 href 屬性作為字符串返回?

[英]How do I use LXML to return href attribute in path as string?

我有打印元素的工作代碼

'//*[@id=all_TorontoBlueJayspitching"]/div/table/tbody/tr/th/a/text()'

從網站https://www.baseball-reference.com/boxes/CHA/CHA202206200.shtml

使用腳本:

import requests

from lxml import html

boxScore = "CHA/CHA202206200"

url = "https://www.baseball-reference.com/boxes/" + boxScore + ".shtml"

page = requests.get(url)

tree = html.fromstring(b''.join(line for line in page.content.splitlines() if b'<!--' not in line and b'-->' not in line))

getTeams = tree.xpath('//*[@class="scorebox"]/div/div/strong/a/text()')

for team in getTeams:

team = team.replace(" ", "")

stringy = '"all_' + team + 'pitching"'

stringx = '//*[@id=' + stringy + ']/div/table/tbody/tr/th/a/text()'


tambellini = tree.xpath(stringx)

print(tambellini)

問題是我不想打印此文本,我想打印其中一條路徑。 這意味着我或多或少地試圖達到

'//*[@id=all_TorontoBlueJayspitching"]/div/table/tbody/tr/th/a'

然后是 /a 中的值 href (在這種情況下是 href=-"/players/b/berrijo01.shtml"

這里的任何指導都會有所幫助。 我知道如何成功打印元素,但我不知道如何將路徑本身作為變量訪問。 謝謝你。

將 stringx 更改為

stringx = '//*[@id=' + stringy + ']/div/table/tbody/tr/th/a/@href'

這應該輸出

[
  '/players/l/lynnla01.shtml', 
  '/players/l/lopezre01.shtml', 
  '/players/g/graveke01.shtml', 
  '/players/k/kellyjo05.shtml'
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM