【问题标题】:Python script to extract a javascript variable from html on a page用于从页面上的 html 中提取 javascript 变量的 Python 脚本
【发布时间】:2021-07-15 13:02:09
【问题描述】:

我的网站页面标题中有以下 javascript:

<script type='text/javascript'>
var gaProperty = 'UA-00000000-1';
var disableStr = 'ga-disable-' + gaProperty;
if ( document.cookie.indexOf( disableStr + '=true' ) > -1 ) {
window[disableStr] = true;
}
function gaOptout() {
document.cookie = disableStr + '=true; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/';
window[disableStr] = true;
}
</script>

我正在尝试使用 python 从 csv 文件中的 url 列表中的每个页面(即 UA-00000000-1)中提取 var gaProperty。我是 python 新手,并从我见过的一些脚本中整理了一个脚本,但它不起作用:

from requests_html import HTMLSession
from urllib.request import urlopen
from bs4 import BeautifulSoup
import csv
import re

list = []
with open('list.csv','r') as csvf: # Open file in read mode
    urls = csv.reader(csvf)
    for url in urls:
        list.append(url) # Add each url to list contents
    

for url in list: 
    page = urlopen(url[0]).read()
    path = " ".join(url)
    soup = BeautifulSoup(page, "lxml")
    data = soup.find_all('script', type='text/javascript')
    gaid = re.search(r'UA-[0-9]+-[0-9]+', data[0].text)
    print(path, gaid)

我得到的错误结果是:

https:www.example.com/contact-us/ None

我需要为每个 url 实现这个期望的输出:

https:www.example.com/contact-us/ UA-00000000-1

知道如何在 Python 中使用它吗?

【问题讨论】:

    标签: python beautifulsoup python-requests urllib python-requests-html


    【解决方案1】:

    我会在模式中包含 var gaProperty,更具体地说,然后确保捕获组延迟捕获后面的 ' 之间的所有内容,即包装 gaid 值。

    import re
    
    html ='''
    <script type='text/javascript'>
    var gaProperty = 'UA-00000000-1';
    var disableStr = 'ga-disable-' + gaProperty;
    if ( document.cookie.indexOf( disableStr + '=true' ) > -1 ) {
    window[disableStr] = true;
    }
    function gaOptout() {
    document.cookie = disableStr + '=true; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/';
    window[disableStr] = true;
    }
    </script>'''
    
    gaid = re.search(r"var gaProperty = '(.*?)'", html).group(1)
    print(f'https:www.example.com/contact-us/{gaid}')
    

    【讨论】:

    • 感谢您的帮助,但它不起作用。请记住,我从我的 csv 文件中抓取了一个 url 列表。我得到的错误是:TypeError:search()缺少1个必需的位置参数:'string'。任何想法如何让它与网址列表一起工作?
    • 您需要将 html 替换为每个请求的响应的文本内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-15
    • 2012-07-23
    • 2019-03-02
    • 2021-04-14
    • 2012-08-16
    • 1970-01-01
    相关资源
    最近更新 更多