【问题标题】:Python - how do I target a class in another class using BeautifulSoup?Python - 如何使用 BeautifulSoup 定位另一个类中的一个类?
【发布时间】:2015-08-17 15:24:20
【问题描述】:

我正在学习用beautifulsoup和Python 3创建爬虫,我遇到了一个问题,我想在一个网站中获取的数据有多个类,这里​​是一个例子:

<tr class="phone">
  <a href="..." class="number"></a>
</tr> 

<tr class="mobile">
  <a href="..." class="number"></a>
</tr> 

这就是我想用 Python 做的事情:

for num in soup.findAll('a', {'class':'mobile -> number'}):
    print(num.string)

我应该怎么做才能定位.mobile .number这个类?

【问题讨论】:

  • 最简单的方法是首先获取所有“移动”字段,然后在它们上运行选择器以查找“数字”。
  • 我想知道字典是如何成为 CSS 选择器的,但你可以试试:{'class':'mobile > number'}

标签: python beautifulsoup web-crawler


【解决方案1】:

您可以使用soup.select 根据CSS selector 查找项目。

from bs4 import BeautifulSoup


html_doc = '''<tr class="phone">
  <a href="tel:+18005551212" class="number"></a>
</tr> 

<tr class="mobile">
  <a href="+13034997111" class="number"></a>
</tr> '''

soup = BeautifulSoup(html_doc)

# Find any tag with a class of "number"
# that is a descendant of a tag with
# a class of "mobile"
mobiles = soup.select(".mobile .number")
print mobiles

# Find a tag with a class of "number"
# that is an immediate descendent
# of a tag with "mobile"
mobiles = soup.select(".mobile > .number")
print mobiles

# Find an <a class=number> tag that is an immediate
# descendent of a <tr class=mobile> tag.
mobiles = soup.select("tr.mobile > a.number")
print mobiles

【讨论】:

  • &gt;' ' CSS 选择器的区别在于,div &gt; p 只会选择 p,它们是 div 的“直接”子代,而 div p 将选择所有 @987654331 @'s inside div,包括孙辈。但是,如果您的 HTML 与您发布的内容一样,那很奇怪 &gt; 不起作用。
【解决方案2】:

find_all() 类为“number”的元素,然后遍历列表并打印parent 的类为“mobile”的元素。

for dom in soup.find_all("a", "number"):
    # this returns a list of class names
    for class in dom.parent()["class"]:     
    if class == "mobile":
        print(dom.string)

或者使用 select() 来设置 CSS 选择器样式

for dom in soup.select("tr.mobile a.number"):
    print(dom.string)

【讨论】:

  • 为什么我会收到这个错误:TypeError: list indices must be integers, not str 并且使用选择选项没有打印任何内容:/
  • @Sia 我的错误dom.parent()['class'] 实际上返回一个列表,因为一个元素可以有很多类,因此那里需要另一个循环。我认为select 代码没有任何问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-16
  • 2022-11-13
  • 1970-01-01
  • 2021-12-21
  • 2014-08-17
  • 1970-01-01
  • 2022-11-14
相关资源
最近更新 更多