Python BeautifulSoup为findAll提供了多个标签

Das*_*pez 36 python beautifulsoup

我正在寻找一种方法来使用findAll按照它们在页面上显示的顺序获取两个标签.

目前我有:

import requests
import BeautifulSoup

def get_soup(url):
    request = requests.get(url)
    page = request.text
    soup = BeautifulSoup(page)
    get_tags = soup.findAll('hr' and 'strong')
    for each in get_tags:
        print each
Run Code Online (Sandbox Code Playgroud)

如果我在一个只有'em'或'strong'的页面上使用它,那么它将为我提供所有这些标签,如果我在两者上使用它将获得'强'标签.

有没有办法做到这一点?我主要关注的是保留标签的查找顺序.

jfs*_*jfs 73

您可以传递一个列表,找到hrstrong标记:

tags = soup.find_all(['hr', 'strong'])
Run Code Online (Sandbox Code Playgroud)

  • @ r0sk:`find_all()`是beautifulsoup4上的正确名称.单击答案中的链接.`findAll()`适用于BeautifulSoup 3,由Beautiful Soup 4取代. (6认同)
  • 我认为soup.findAll(['hr','strong'])可以完成这项工作,find_all不会运行. (2认同)

Ter*_*ryA 8

使用正则表达式:

import re
get_tags = soup.findAll(re.compile(r'(hr|strong)'))
Run Code Online (Sandbox Code Playgroud)

表达式r'(hr|strong)'将找到hr标签或strong标签.