且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用BeautifulSoup bs4获取HTML标签的内部文本值?

更新时间:2023-08-25 13:01:28

使用.text从标签中获取文本。

Use .text to get the text from the tag.

oname = soup.find("title")
oname.text

或只是 soup.title.text

In [4]: from bs4 import BeautifulSoup    
In [5]: import  requests
In [6]: r = requests.get("http://***.com/questions/27934387/how-to-retrieve-information-inside-a-tag-with-python/27934403#27934387")    
In [7]: BeautifulSoup(r.content).title.text
Out[7]: u'html - How to Retrieve information inside a tag with python - Stack Overflow'

要打开一个文件并使用文本作为名字,就像使用其他任何字符串一样简单地使用它:

To open a file and use the text as the name simple use it as you would any other string:

with open(oname.text, 'w') as f