Y小y 发表于 2020-8-10 23:23:13

标签问题

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<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 href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')
import re
def has_class_but_no_id(tag):
    return tag.has_attr('class') and not tag.has_attr('id')
soup.find_all(has_class_but_no_id)

为什么我这里还是返回了<a>标签?还有调用has_class_but_no_id不需要传参数的吗?

zltzlt 发表于 2020-8-11 09:16:20

1. 因为这里 Beautiful Soup 把<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>这个 p 标签看成是一个整体了

2. 这里的意思是函数本身作为参数传入,不需要加上表示调用的括号

海皇 发表于 2020-8-11 09:33:39

那是因为你这一行已经错了不是这个
<a href="http://example.com/elsie" class="sister" id="link1"> Elsie < / a>,
而是这个
<a href="http://example.com/elsie" class="sister" id="link1"> Elsie </a>,

海皇 发表于 2020-8-11 09:34:31

你的代码打错了不是这个
<a href="http://example.com/elsie" class="sister" id="link1"> Elsie < / a>,
而是这个
<a href="http://example.com/elsie" class="sister" id="link1"> Elsie </a>,
页: [1]
查看完整版本: 标签问题