Python beautifulsou在字符串后匹配regex

2024-09-22 16:39:01 发布

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

我用BeautifulSoup和Python来刮一个网页。我有BS元素

a = soup.find('div', class_='section lot-details')

它返回一系列列表对象,如下所示。你知道吗

<li><strong>Location:</strong> WA - 222 Welshpool Road, Welshpool</li>
<li><strong>Deliver to:</strong> Pickup Only WA</li>

我想在每次str后返回文本

WA - 222 Welshpool Road, Welshpool
Pickup Only WA

我怎么才能从BS对象中得到这个呢?我不确定正则表达式,也不确定它如何与BeautifulSoup交互。你知道吗


Tags: 对象div元素网页onlybslifind
2条回答

你真的不需要正则表达式。如果列表中有li标记:

>>> for li in li_elems:
...     print li.find('strong').next_sibling.strip()

WA - 222 Welshpool Road, Welshpool
Pickup Only WA

这是假设在li中只有一个strong元素,然后是文本。你知道吗

或者,或者:

>>> for li in li_elems:
...     print li.contents[1].strip()

WA - 222 Welshpool Road, Welshpool
Pickup Only WA

(?:</strong>)(.*)(?:</li>)捕获字段\1(.*)将完成这项工作。你知道吗

Python代码示例:

In [1]: import re
In [2]: test = re.compile(r'(?:</strong>)(.*)(?:</li>)')
In [3]: test.findall(input_string)
Out[1]: [' WA - 222 Welshpool Road, Welshpool', ' Pickup Only WA']

在这里检查https://regex101.com/r/fD0fZ9/1

相关问题 更多 >