Python 3.6 BeautifulSoup循环后打印空白区域
我在这段下面的beautifulsoup页面上使用了“三姐妹”HTML。我是beautiful soup的新手,我不能让这个循环输出我可以在for/in循环中使用的信息。我可以让名字单独打印出来,但我不能让它们充当变量Python 3.6 BeautifulSoup循环后打印空白区域,python,python-3.x,loops,beautifulsoup,Python,Python 3.x,Loops,Beautifulsoup,我在这段下面的beautifulsoup页面上使用了“三姐妹”HTML。我是beautiful soup的新手,我不能让这个循环输出我可以在for/in循环中使用的信息。我可以让名字单独打印出来,但我不能让它们充当变量 <pre> <html> <head> <title> The Dormouse's story </title> </head>
<pre>
<html>
<head>
<title>
The Dormouse's story
</title>
</head>
<body>
<b></b>
<p class="title">
<b>
The Dormouse's story
</b>
</p>
<p class="story">
Once upon a time there were three little sisters; and their names were
<a class="sister" href="http://example.com/elsie" id="link1">
Elsie
</a>
,
<a class="sister" href="http://example.com/lacie" id="link2">
Lacie
</a>
and
<a class="sister" href="http://example.com/tillie" id="link2">
Tillie
</a>
; and they lived at the bottom of a well.
</p>
<p class="story">
<b>
The End
</b>
</p>
</body>
</html>
</pre>
以下内容出现在pycharm的运行窗口中
Elsie
如果我将其更改为:
<a class="sister" href="http://example.com/elsie" id="link1">
Elsie
</a>
<a class="sister" href="http://example.com/lacie" id="link2">
Lacie
</a>
<a class="sister" href="http://example.com/tillie" id="link2">
Tillie
</a>
然后输出所有三个名称:
attr = {'class':'sister'}
father = soup.find_all('a',attrs=attr)
for child in father:
print(child.string)
产生:
attr = {'class':'sister'}
father = soup.find_all('a',attrs=attr)
for child in father:
print(child.string)
for child in father:
if child == 'Elsie':
print(child)
如果我这样做了:
Elsie
Lacie
Tillie
它仍然只打印:
[<a class="sister" href="http://example.com/elsie" id="link1">
Elsie
</a>, <a class="sister" href="http://example.com/lacie" id="link2">
Lacie
</a>, <a class="sister" href="http://example.com/tillie" id="link2">
Tillie
</a>]
如果你检查一下父亲身上有什么,你会看到:
if '<a class="sister" href="http://example.com/elsie" id="link1"> Elsie </a>' == "Elsie":
因此,即使标签中存在字符串Elsie,它也将返回False
要检查标记是否具有所需的字符串,可以使用.text方法,该方法将返回带有空格和换行符的Elsie。所以你需要脱掉它
最后,在进行这些更改时,您可以使用以下方法:
for child in father:
if child.text.strip() == 'Elsie':
print(child.text.strip())
或者,只需按如下方式打印文本:
什么是three-sisters.html?在代码中添加html。如果没有文本,您希望我们如何帮助您?同时添加您的预期输出。刚刚发布。很抱歉。使用if child.text.strip=='Elsie':谢谢你!成功了。老兄,我怎么能自己搞清楚这件事?我到处都试过strip和text。@NickolasKent Python的好处之一是,您可以交互地运行此代码,通常只需键入Python并逐行输入代码。然后你可以使用像dirvariable或helpvariable这样的内置工具来检查对象,看看你能用它做些什么。我真的很想了解为什么事情会发生,而不仅仅是复制东西。既然你是SO的新手,请阅读以下内容:。
Elsie
Lacie
Tillie
[<a class="sister" href="http://example.com/elsie" id="link1">
Elsie
</a>, <a class="sister" href="http://example.com/lacie" id="link2">
Lacie
</a>, <a class="sister" href="http://example.com/tillie" id="link2">
Tillie
</a>]
if '<a class="sister" href="http://example.com/elsie" id="link1"> Elsie </a>' == "Elsie":
for child in father:
if child.text.strip() == 'Elsie':
print(child)
for child in father:
if child.text.strip() == 'Elsie':
print(child.text.strip())