使用 Beautiful Soup 提取同级文本节点

Col*_*tek 4 python beautifulsoup

我正在尝试使用美丽的汤获取某些文本,但我不知道如何在 /strong 标签后获取文本。我找到了我正在寻找的内容,但只想要某些元素。

res = requests.get('http://www.fangraphs.com/statss.aspx?playerid=10155&position=OF')
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text, "lxml")
gamescore = soup.select('#content > table > tr > td > table > tr > td > div')
Run Code Online (Sandbox Code Playgroud)

输出: 出生日期: 1991 年 8 月 7 日(25 岁,6 米,12 天)     蝙蝠/投掷: R/R

是否有可能只得到出生日期和 R/R?

Jos*_*ier 5

您可以<strong>根据文本选择元素,然后使用next_sibling属性选择相邻的同级节点。

birthday = soup.find('strong', text='Birthdate:').next_sibling.strip()
gamescore = soup.find('strong', text='Bats/Throws:').next_sibling.strip()
Run Code Online (Sandbox Code Playgroud)

输出:

> print(birthday, gamescore)
> 8/7/1991 (25 y, 6 m, 12 d) R/R
Run Code Online (Sandbox Code Playgroud)

如果要选择每个<strong>元素及其下一个同级节点,则可以使用以下命令:

elements = soup.select('#content > table table div > strong')

for element in elements:
    print(element.text, element.next_sibling)
Run Code Online (Sandbox Code Playgroud)

输出:

> Birthdate:  8/7/1991 (25 y, 6 m, 12 d)     
> Bats/Throws:  R/R     
> Height/Weight:  6-1/235     
> Position:  OF
> Contract:
Run Code Online (Sandbox Code Playgroud)