Skip to main content
 首页 » 编程设计

python之如何解析 Python3 BeautifulSoup 中的 onclick() 文本

2024年11月01日8langtianya

我有以下 HTML:

<td id="uprnButton0"> 
  <button type="button" 
    onclick="changeText('uprnButton0','Loading');populAddr('14 PLACE NAME TOWN POSTCODE'); 
    getobject('divAddress').innerHTML = ''; 
    GetInfoAndRoundsFor('123456789123','SWN');"  
    title="Get Calendar for this address" 
    >Show 
  </button> 
</td> 

我想在 populAddr 和 GetInfoAndRoundsFor 中获取文本,即分别是字符串“14 PLACE NAME TOWN POSTCODE”和“123456789123”。

到目前为止我已经尝试过:

button_click_text = address.find('button').get('onclick') 

这让我得到了完整的 onClick 字符串,这很棒。是让特定子串做一些切片的唯一方法吗?

我已经试过了:

   string = """changeText('uprnButton1','Loading');populAddr('14 PLACE NAME TOWN POSTCODE');getobject('divAddress').innerHTML = '';GetInfoAndRoundsFor('123456789123','SWN');""" 
    string_before = "populAddr('" 
    string_after = "');getobject" 
 
    print(string[string.index(string_before)+len(string_before):string.index(string_after)]) 

这确实有效,但看起来一团糟。这里有最佳实践吗?

实际上只是认为这可能会更好:

string_split = string.split("'") 
print(string_split[5]) 
print(string_split[11]) 

请您参考如下方法:

您应该能够使用以下两种惰性正则表达式模式

import re 
 
html ='''<td id="uprnButton0"> 
  <button type="button" 
    onclick="changeText('uprnButton0','Loading');populAddr('14 PLACE NAME TOWN POSTCODE'); 
    getobject('divAddress').innerHTML = ''; 
    GetInfoAndRoundsFor('123456789123','SWN');"  
    title="Get Calendar for this address" 
    >Show 
  </button> 
</td>''' 
 
p1 =re.compile(r"populAddr\('(.*?)'") 
p2 = re.compile(r"GetInfoAndRoundsFor\('(.*?)'") 
print(p1.findall(html)[0]) 
print(p2.findall(html)[0]) 

一个解释(两个原理相同)

您可以将 html 变量替换为 response.text 或 button_click_text,其中 response.text 是 requests 响应.text