我想抓取一个网页,并仅返回GTM容器ID(在下面的示例中为GTM-5LS3NZ)。该代码不应查找确切的容器ID,而应查找模式,因为我将在多个站点上使用它。
到目前为止,我可以搜索标题并打印包含GTM的整个文本,但是我不知道如何将搜索结果和正则表达式一起格式化以仅返回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。
答案 0 :(得分:1)
由于评论中的帮助,我现在已经解决了。这就是我的追求:
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])
答案 1 :(得分:1)
几天前我做了类似的事情,然后快速重写就给了我
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作为输出。
答案 2 :(得分:0)
您还可以从适当的评论中提取
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