我正在尝试访问一个元素

<script type="text/javascript">ReportPopper("http://asd.asd.asd/ReportOutput/asd-asd-41cc-asd-asd.xls");<script>

使用beautifulsoup,不幸的是,我不确定如何访问ReportPopper部分并将其分配给使用Python的变量

抱歉,如果已经回答。
我尝试在find('ReportPopper')中添加ReportPopper并给我一个none元素。
import requests
import io
import os
from bs4 import BeautifulSoup


participation = requests.post(url=report_post_url,data=request_post_report_form,headers=report_post_headers,stream=True)
print(participation)


soup = BeautifulSoup(participation.text, 'html.parser')

for n in soup.find_all('script'):
    javascript = n['ReportPopper']
    print(javascript)

我想得到的最终结果是:
javascript = "http://asd.asd.asd/ReportOutput/asd-asd-41cc-asd-asd.xls"
作为我的输出:
Traceback (most recent call last):
  File "c:\Users\John asd\Documents\GitHub\asd.net\testing.py", line 184, in <module>
    javascript = n['ReportPopper']
  File "C:\Users\John asd\asd\Local\Programs\Python\Python37\lib\site-packages\bs4\element.py", line 1016, in __getitem__
    return self.attrs[key]
KeyError: 'ReportPopper'

最佳答案

re.compile()返回regular expression object,这意味着h是正则表达式对象。

regex对象具有自己的match方法,带有可选的pos和endpos参数:

regex.match(string[, pos[, endpos]])

from bs4 import BeautifulSoup
import  re

html = """<script>ReportPopper("http://asd.asd.asd/ReportOutput/asd-asd-41cc-asd-asd.xls");</script>"""

soup = BeautifulSoup(html, 'lxml')
script = soup.find_all("script")

pattern = re.compile('ReportPopper(.*);')

for i in script:
    strObj = i.text
    match = pattern.search(strObj)
    if match:
        print(strObj.split("ReportPopper(")[1][:-2])

O / P:
"http://asd.asd.asd/ReportOutput/asd-asd-41cc-asd-asd.xls"

关于javascript - 如何使用美丽汤访问此项目,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56488680/

10-11 17:50