如何获取 soup.select 的值?
How do I get the value of a soup.select?
<h2 class="hello-word"><a href="http://www.google.com">Google</a></h2>
如何获取 a
标签 (Google) 的值?
print soup.select("h2 > a")
returns 整个 a 标签,我只想要值。此外,页面上可能有多个 H2。我如何筛选带有 class hello-word
的那个?
试试这个:
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('<h2 class="hello-word"><a href="http://www.google.com">Google</a></h2>', 'html.parser')
>>> soup.text
'Google'
您也可以改用 lxml.html
库
>>> import lxml.html
>>> from lxml.cssselect import CSSSelector
>>> txt = '<h2 class="hello-word"><a href="http://www.google.com">Google</a></h2>'
>>> tree = lxml.html.fromstring(txt)
>>> sel = CSSSelector('h2 > a')
>>> element = sel(tree)[0]
>>> element.text
Google
您可以在 CSS 选择器中的 h2
上使用 .hello-word
,对于 select 只有 h2
带有 class [=15] 的标签=] 然后 select 它的 child a
。还有 soup.select()
returns 所有可能匹配项的列表,因此您可以轻松地遍历它并调用每个元素 .text
来获取文本。示例 -
for i in soup.select("h2.hello-word > a"):
print(i.text)
Example/Demo(我添加了一些我自己的元素,其中一个元素 class 略有不同以显示 selector 的工作)-
>>> from bs4 import BeautifulSoup
>>> s = """<h2 class="hello-word"><a href="http://www.google.com">Google</a></h2>
... <h2 class="hello-word"><a href="http://www.google.com">Google12</a></h2>
... <h2 class="hello-word2"><a href="http://www.google.com">Google13</a></h2>"""
>>> soup = BeautifulSoup(s,'html.parser')
>>> for i in soup.select("h2.hello-word > a"):
... print(i.text)
...
Google
Google12
<h2 class="hello-word"><a href="http://www.google.com">Google</a></h2>
如何获取 a
标签 (Google) 的值?
print soup.select("h2 > a")
returns 整个 a 标签,我只想要值。此外,页面上可能有多个 H2。我如何筛选带有 class hello-word
的那个?
试试这个:
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('<h2 class="hello-word"><a href="http://www.google.com">Google</a></h2>', 'html.parser')
>>> soup.text
'Google'
您也可以改用 lxml.html
库
>>> import lxml.html
>>> from lxml.cssselect import CSSSelector
>>> txt = '<h2 class="hello-word"><a href="http://www.google.com">Google</a></h2>'
>>> tree = lxml.html.fromstring(txt)
>>> sel = CSSSelector('h2 > a')
>>> element = sel(tree)[0]
>>> element.text
Google
您可以在 CSS 选择器中的 h2
上使用 .hello-word
,对于 select 只有 h2
带有 class [=15] 的标签=] 然后 select 它的 child a
。还有 soup.select()
returns 所有可能匹配项的列表,因此您可以轻松地遍历它并调用每个元素 .text
来获取文本。示例 -
for i in soup.select("h2.hello-word > a"):
print(i.text)
Example/Demo(我添加了一些我自己的元素,其中一个元素 class 略有不同以显示 selector 的工作)-
>>> from bs4 import BeautifulSoup
>>> s = """<h2 class="hello-word"><a href="http://www.google.com">Google</a></h2>
... <h2 class="hello-word"><a href="http://www.google.com">Google12</a></h2>
... <h2 class="hello-word2"><a href="http://www.google.com">Google13</a></h2>"""
>>> soup = BeautifulSoup(s,'html.parser')
>>> for i in soup.select("h2.hello-word > a"):
... print(i.text)
...
Google
Google12