Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.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 BeautifulSoup,简单正则表达式问题_Python_Regex_Python 2.7_Beautifulsoup - Fatal编程技术网

Python BeautifulSoup,简单正则表达式问题

Python BeautifulSoup,简单正则表达式问题,python,regex,python-2.7,beautifulsoup,Python,Regex,Python 2.7,Beautifulsoup,我只是在regex上遇到了一个障碍,不知道为什么这不起作用 下面是BeautifulSoup doc说的话: soup.find_all(class_=re.compile("itl")) # [<p class="title"><b>The Dormouse's story</b></p>] 所以,我只是重复BS4文档,只是我的正则表达式不起作用。如果我将\d{1}替换为4(如最初在html中所示),它就成功了 在正则表达式中尝试“\\d”。它

我只是在regex上遇到了一个障碍,不知道为什么这不起作用

下面是BeautifulSoup doc说的话:

soup.find_all(class_=re.compile("itl"))
# [<p class="title"><b>The Dormouse's story</b></p>]
所以,我只是重复BS4文档,只是我的正则表达式不起作用。如果我将
\d{1}
替换为
4
(如最初在html中所示),它就成功了

在正则表达式中尝试“\\d”。它可能将“\d”解释为试图逃避“d”

或者,原始字符串应该可以工作。只需在正则表达式前面加一个“r”,如下所示:

re.compile(r"pos_text pos3_l_\d{1}")

我不完全确定,但这对我很有效:

soup.find(attrs={'class':re.compile('pos_text pos3_l_\d{1}')})

您不是为某个类进行匹配,而是为特定顺序的特定类组合进行匹配

从:

您还可以搜索class属性的确切字符串值:
css_soup.find_all(“p”,class=“身体三振”)
#[

]但搜索字符串值的变体将不起作用: css_soup.find_all(“p”,class=“三振体”) # []

因此,您应该为post_文本设置fist match,然后在结果中尝试与该搜索匹配中的regexp进行匹配,这是文档中的

:在所有版本的Beautiful Soup中都有类_u的快捷方式。任何find()类型方法的第二个参数称为attrs,传入attrs的字符串将作为CSS类搜索该字符串:Oh neat。我从来没有注意到。为什么d需要转义?
d
不需要转义。“\`需要转义。嗯,我已经用了
\d
很多次了,实际上从来没有转义过反斜杠。反正我现在也试过了,但没用。
re.compile(r"pos_text pos3_l_\d{1}")
soup.find(attrs={'class':re.compile('pos_text pos3_l_\d{1}')})
You can also search for the exact string value of the class attribute:

css_soup.find_all("p", class_="body strikeout")
# [<p class="body strikeout"></p>] But searching for variants of the string value won’t work:

css_soup.find_all("p", class_="strikeout body")
# []