如何通过Python中的Beautiful Soup在类和类名中找到包含空格的文本?

时间:2016-11-15 08:38:44

标签: python-3.x web-scraping beautifulsoup

例如,我有一个<div>的班级和一个有空格的班级。

<div class="class name having spaces"> </div>

2 个答案:

答案 0 :(得分:3)

$sql_query="UPDATE users SET password='".$u_password."' 
            WHERE name='".$u_name."' AND contact='".$u_contact."'";

出:

from bs4 import BeautifulSoup
doc ='''<div class='the value'><\div>'''
soup = BeautifulSoup(doc, 'lxml')

print(soup.find_all(attrs={'class':'the value'}))
print(soup.find_all(class_='the value'))
# if the part of value is uniqu, you can use them separately
print(soup.find_all(class_='the'))        
print(soup.find_all(class_='value'))

答案 1 :(得分:2)

有空格意味着该条目有两个类应用于它,例如myclass适用于此。如果您正在查找包含这两个类的所有<div>条目,那么我建议您使用BeautifulSoup的select()函数,如下所示:

from bs4 import BeautifulSoup

html ='''
    <div class='my class'>test1</div>
    <div class='class my'>test2</div>
    <div class='my other class'>test3</div>
    <div class='my other'>test4</div>
    <div class='myclass'>test5</div>'''

soup = BeautifulSoup(html, 'html.parser')

for div in soup.select('div.my.class'):
    print(div.text)

这将捕获定义中(以任何顺序)两个类都存在的所有位置。给你以下输出:

test1
test2
test3