Python正则表达式匹配但不包括字符靓汤

2024-09-29 03:34:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用美丽的汤和请求从一个网页上写下信息,我试图得到一个书名列表,只是标题,不包括文字标题=在标题的字体。在

Example text='一堆垃圾标题=book1更多垃圾文本标题=book2'

我得到的是titleList=['title=book1','title=book2']

我想要标题列表=['book1','book2']

我尝试过匹配组,这确实将title=和book1分开,但我不确定如何将group(2)添加到列表中。在

titleList = []

def getTitle(productUrl):

  res = requests.get(productUrl, headers=headers)
  res.raise_for_status()

  soup = bs4.BeautifulSoup(res.text, 'lxml')
  title = re.compile(r'title=[A-Za-z0-9]+')
  findTitle = title.findall(res.text.strip())
  titleList.append(findTitle)

Tags: text信息网页标题列表titleres垃圾
2条回答

re.findall与捕获组一起使用可以做到:

>>> import re
>>> text = 'a bunch of junk title=book1 more junk text title=book2'
>>> re.findall(r'title=(\S+)', text)
['book1', 'book2']
>>>

您的正则表达式没有捕获组。您还应该注意,findall返回一个列表,因此应该使用extend而不是{}(除非您希望titleList是一个列表列表列表)。在

title = re.compile(r'title=([A-Za-z0-9]+)')   # note parenthesis
findTitle = title.findall(res.text.strip())
titleList.extend(findTitle)   # using extend and not append

一个独立的例子:

^{pr2}$

相关问题 更多 >