Python和BeautifulSoup在htm中查找文本字符串

2024-10-01 07:10:16 发布

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

具有以下为键盘检查某个网页的功能

def checkString():   
    url_a = 'https://launchstudio.bluetooth.com/ListingDetails/50756'
    r_a = requests.get(url_a)
    soup_a = BeautifulSoup(r_a.text)

    for blem in soup_a(text=re.compile(r'RFCOMM')):
        return True

    return False 

已经验证了我的soup\u a与url的视图源是相同的,但是我的搜索似乎只会返回包含在head标签中的结果,并且很难找出原因。有什么建议吗?你知道吗

Python版本2.7.5


Tags: texthttps功能comurl网页returndef
1条回答
网友
1楼 · 发布于 2024-10-01 07:10:16

您需要将lxml传递给BeautifulSoup类。此外,如果找到匹配项,return True将跳出for循环。因此,如果在head标签中确实找到了RFCOMM,则循环将退出,不再注册匹配项。最好使用列表理解并确定是否找到匹配项:

from bs4 import BeautifulSoup as soup
import urllib.request as urllib
import re
def checkString():   
   url_a = 'https://launchstudio.bluetooth.com/ListingDetails/50756'
   s = soup(str(urllib.urlopen(url_a).read()), 'lxml')
   return bool([i for i in s(text=re.compile(r'RFCOMM'))])

print(checkString())

输出:

True

相关问题 更多 >