用漂亮的汤从网站上抓取文本字符串

Scrape string of text from website with beautiful soup

我想抓取一个网页和 只是 return GTM(Google 标签管理器)容器 ID(在下面的例子中是GTM-5LS3NZ)。该代码不应查找确切的容器 ID,而是查找模式,因为我将在多个站点上使用它。

到目前为止,我可以搜索头部并打印包含 GTM 的整段文本,但我不知道如何将查找和正则表达式一起格式化为 return GTM-5LS3NZ(在此示例)。

import urllib3
import re
from bs4 import BeautifulSoup

http = urllib3.PoolManager()

response = http.request('GET', "https://www.observepoint.com/")
soup = BeautifulSoup(response.data,"html.parser")

GTM = soup.head.findAll(text=re.compile(r'GTM'))
print(GTM)

注意:GTM ID 可以包含 6 或 7 个字母数字字符,因此我希望容器 ID 的正则表达式类似于 ^GTM-[A-Z0-9] - 我不知道如何指定6 或 7 个字符。

澄清我所追求的。 如果您 运行 上面的代码,您将得到以下内容。

["(function (w, d, s, l, i) {\n      w[l] = w[l] || [];\n      w[l].push({\n        'gtm.start': new Date().getTime(),\n        event: 'gtm.js'\n      });\n      var f = d.getElementsByTagName(s)[0],\n        j = d.createElement(s),\n        dl = l != 'dataLayer' ? '&l=' + l : '';\n      j.async = true;\n      j.src =\n        'https://www.googletagmanager.com/gtm.js?id=' + i + dl;\n      f.parentNode.insertBefore(j, f);\n    })(window, document, 'script', 'dataLayer', 'GTM-5LS3NZ');"]

我只想要 GTM-5LS3NZ。

感谢评论中的帮助,我现在已经解决了。这就是我想要的:

import re
from bs4 import BeautifulSoup

http = urllib3.PoolManager()

response = http.request('GET', "https://www.observepoint.com/")
soup = BeautifulSoup(response.data,"html.parser")

GTM = soup.head.findAll(text=re.compile(r'GTM'))
print(re.search("GTM-[A-Z0-9]{6,7}",str(GTM))[0])

几天前我做了类似的事情,快速重写后得到:

import urllib3
import re
from bs4 import BeautifulSoup

http = urllib3.PoolManager()

response = http.request('GET', "https://www.observepoint.com/")
soup = BeautifulSoup(response.data,"html.parser")

pattern  =re.compile(r'GTM-([a-zA-Z0-9]{6,7})')
found = soup.head.find(text=pattern)
if found:
    match = pattern.search(found)
    if match:
        print(match.group(1))

这给了我 GTM-5LS3NZ 作为输出。

您也可以从适当的评论中摘录

import requests
from bs4 import BeautifulSoup, Comment

r = requests.get('https://www.observepoint.com/')
soup = BeautifulSoup(r.content, 'lxml')
for comment in soup.findAll(text=lambda text:isinstance(text, Comment)):
    if 'iframe' in comment:
        soup = BeautifulSoup(comment, 'lxml')
        id = soup.select_one('iframe')['src'].split('=')[1]
        print(id)
        break