Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在find_all of Beautifulsoup中使用正则表达式_Python_Regex_Beautifulsoup - Fatal编程技术网

Python 在find_all of Beautifulsoup中使用正则表达式

Python 在find_all of Beautifulsoup中使用正则表达式,python,regex,beautifulsoup,Python,Regex,Beautifulsoup,我正试图清理tumblr归档文件,div类标记如图所示 该类以“post_micro”开头,我尝试使用正则表达式,但失败了 soup.find_all(class_=re.compile('^post post_micro') 我试着在课堂上使用find_all中的函数 def func(x): if str(x).startswith('post_tumblelog'): return True 并将其用作: soup.find

我正试图清理tumblr归档文件,div类标记如图所示

该类以“post_micro”开头,我尝试使用正则表达式,但失败了

soup.find_all(class_=re.compile('^post post_micro') 
我试着在课堂上使用find_all中的函数

def func(x):                 
    if str(x).startswith('post_tumblelog'):
        return True
并将其用作:

soup.find_all(class_=func)
上面的工作很好,我得到了我需要的。但是我想知道如何使用正则表达式,为什么在func(x)中


当类名以“post post_micro”开头时计算为True。在BeautifulSoup 4中,您可以使用,因为它可以接受CSS属性选择器。在您的情况下,您将使用属性选择器
[class^=“post\u-turnlog”]
,它将选择以字符串
post\u-turnlog
开头的
class
属性

soup.select('[class^="post_tumblelog"]')
或者,您也可以使用:

soup.find_all(class_=lambda x: x and x.startswith('post_tumblelog'))
作为旁注,看起来您缺少了一个括号,以下方法有效:

soup.find_all(class_=re.compile('^post_tumblelog'))  

Using.select给出错误:不支持或无效的CSS选择器:“[class^=“post"这两个选项中的其余部分使用的是“post_Tumblog”,而不是“post-post_-micro”,我不知道为什么会出现这种情况。是的,其中两个使用lambda函数和正则表达式,但传递的参数必须是“post_-Tumblog”@sandepp-我刚刚用字符串
post_-Tumblog
post-post_-micro对其进行了测试
,它们都起作用了。你介意发布你的HTML和你正在使用的BeautifulSoup的哪个版本吗?bs4版本是4.3.2,我认为这是类值中的空间问题,我昨晚刚刚选择了BeautifulSoup,但不知道css和HTML。所以我认为需要做更多的工作
soup.find_all(class_=re.compile('^post_tumblelog'))