Python Beautiful Soup 在 div 标签本身中提取数据
Python Beautiful Soup extracting data within a div tag itself
我正在尝试使用 Python beautifulSoup 从 HTML 文件中提取数据。 HTML下面一行是我感兴趣的
<div class="myself" title="Name@email.com [11:07:27 AM]">
<nobr>Name</nobr></div>
我想提取标题(带有电子邮件和时间戳)。我可以使用...
访问 class
find('div', attrs={'class':'myself'}))
我可以从那里打印 div
的全部内容或 div 中标签中的信息,但我不知道如何获取 title
因为它在同一个 div
标签内
可以用这个方法
>>>import bs4
>>>html_string = "<div class="myself" title="Name@email.com [11:07:27 AM]">
<nobr>Name</nobr></div>"
>>>title_string = bs4.BeautifulSoup(html_string).div.attrs['title']
>>>print(title_string)
'Name@email.com [11:07:27 AM]'
Attributes can be retrieved in a dictionary-like manner:
A tag may have any number of attributes. You can access a tag’s
attributes by treating the tag like a dictionary.
from bs4 import BeautifulSoup
soup = BeautifulSoup(data)
div = soup.find("div", class_="myself", title=True)
print(div["title"])
我正在尝试使用 Python beautifulSoup 从 HTML 文件中提取数据。 HTML下面一行是我感兴趣的
<div class="myself" title="Name@email.com [11:07:27 AM]">
<nobr>Name</nobr></div>
我想提取标题(带有电子邮件和时间戳)。我可以使用...
访问 classfind('div', attrs={'class':'myself'}))
我可以从那里打印 div
的全部内容或 div 中标签中的信息,但我不知道如何获取 title
因为它在同一个 div
标签内
可以用这个方法
>>>import bs4
>>>html_string = "<div class="myself" title="Name@email.com [11:07:27 AM]">
<nobr>Name</nobr></div>"
>>>title_string = bs4.BeautifulSoup(html_string).div.attrs['title']
>>>print(title_string)
'Name@email.com [11:07:27 AM]'
Attributes can be retrieved in a dictionary-like manner:
A tag may have any number of attributes. You can access a tag’s attributes by treating the tag like a dictionary.
from bs4 import BeautifulSoup
soup = BeautifulSoup(data)
div = soup.find("div", class_="myself", title=True)
print(div["title"])