当文本不在<> ... </>本身内时,使用BeautifulSoup在强标签之后获取文本

时间:2020-07-24 00:02:34

标签: python beautifulsoup

我要抓取这个网站:https://eintaxid.com/companies/a/?page=1

我已成功提取公司名称:

r = requests.get('https://eintaxid.com/companies/a/?page=1')
soup = BeautifulSoup(r.content, "html.parser")

# outputs all strong tags
for tag in soup.find_all('strong'):
    print(tag.text)

我可以很容易地隔离出公司名称:

r = requests.get('https://eintaxid.com/companies/a/?page=1')
soup = BeautifulSoup(r.content, "html.parser")
table = soup.find_all('strong')

comp_list = []

# loop to extract just the company names from the strong tags, then using the a tags
for j in table:
    td = j.find_all(['a'])
    row = [i.text for i in td]
    comp_list.append(row)

# puts company names into a pandas df
comp_list = list(filter(lambda x: len(x) > 0, comp_list))
comp_list = pd.DataFrame(comp_list, columns = ['Company']).reset_index(drop = True)
comp_list

尽管如此,我还是无法提取EIN号码。 <strong>EIN Number:</strong>显而易见,我可以从上面的第一个代码块中提取出来。但是,如何获得实际数字?如以下屏幕截图所示,是 98-1455367吗?

Screenshot of page html

作为参考,我将在熊猫df中将EIN号放在每个公司的旁边-但要等到我自己提取EIN号之后才能真正做到这一点。

1 个答案:

答案 0 :(得分:2)

请参考docs,您可能想使用标签的next_sibling,首先捕获强标签,然后从上下文中获取下一项:

strong_element.next_sibling    # contains "EIN number"

在此上下文中,“同级”是下一个节点,而不是下一个元素/标签。元素的下一个节点是文本节点,因此您可以获取想要的文本。