使用Beautiful Soup提取兄弟文本节点

时间:2017-02-20 01:30:38

标签: 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')

输出: 出生日期: 8/7/1991(25 y,6 m,12 d) Bats / Throws: R / R

是否有可能仅将生日和R / R从中获得?

1 个答案:

答案 0 :(得分:4)

您可以根据文本选择<strong>元素,然后使用next_sibling property选择相邻的兄弟节点。

birthday = soup.find('strong', text='Birthdate:').next_sibling.strip()
gamescore = soup.find('strong', text='Bats/Throws:').next_sibling.strip()

输出:

> print(birthday, gamescore)
> 8/7/1991 (25 y, 6 m, 12 d) R/R

如果要选择每个<strong>元素及其下一个兄弟节点,则可以使用以下内容:

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

for element in elements:
    print(element.text, element.next_sibling)

输出:

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