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

标签 python python-3.x beautifulsoup

我有以下 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])

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

enter image description here

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

关于python - 如何解析 Python3 BeautifulSoup 中的 onclick() 文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57723777/

相关文章:

python - 如何从python中已经打开的网页中提取css数据

python - python 中的 matplotlib - 使用 x 轴中的相应值和大数绘制图形

python - 是否可以在 Emacs 中将 Ropemacs 与 TRAMP 一起使用?

python - Python 中是否有允许在单个文件中管理虚拟文件系统的库?

python - 如何在Python中通过动态传递 'value'来获取 'enum member name'?

Python Web 抓取重定向到其他页面的页面

Python Flask SQL 注册登录页面 "hash must be unicode or bytes, not long"

Python:如何检查对象键值对的数据类型?

python - 'self' 作为 PyQt5 中的参数有什么区别

python - 使用 beautifulsoup 通过 div 标签查找 div 文本