【问题标题】:How to scrape javascript text using beautifulsoup如何使用 beautifulsoup 抓取 javascript 文本
【发布时间】:2018-07-03 16:29:51
【问题描述】:

我正在尝试使用 Python 获取由 html 中的外部脚本生成的文本:

<td class="headerlast item" rowspan="2" colspan="1" id="Party_ATP021_1">
<div id="Party_ATP021mod"></div>

<script type="text/javascript">
var myTooltip = new YAHOO.widget.Tooltip("Party_ATP021tip", { 
context:"Party_ATP021_1", text:"Sozialdemokratische Partei Österreichs 
(Social Democratic Party of Austria)", showDelay:1000, 
autodismissdelay:5000,iframe:true, preventoverlap:true } );
</script>
SPÖ
</td>

我试图获得:“SPÖ”但没有成功。

到目前为止,我能够获得脚本中使用的 id:

import requests
from bs4 import BeautifulSoup
import re
from fake_useragent import UserAgent
ua = UserAgent()

link = 'http://eed.nsd.uib.no/webview/velocity?v=2&mode=cube&cube=http%3A%2F%2F129.177.90.166%3A80%2Fobj%2FfCube%2FSIEP2004%21Display_C1&study=http%3A%2F%2F129.177.90.166%3A80%2Fobj%2FfStudy%2FSIEP2004%21Display'

headers ={'user-agent': str(ua.random)}
result_page = BeautifulSoup(requests.get(link, headers=headers, 
timeout=10).text, 'html.parser')

for td in result_page.find_all('td', {'class': 'headerlast item'})[1:]:
    print(td.get('id'))

有什么帮助吗? 非常感谢!

【问题讨论】:

    标签: python-3.x web-scraping beautifulsoup requestscope


    【解决方案1】:

    对于您的示例数据,您可以将 select 与 css 选择器 td.headerlast.item script 一起使用,并在脚本元素之后获取 next_sibling

    html_doc = """
    <td class="headerlast item" rowspan="2" colspan="1" id="Party_ATP021_1">
    <div id="Party_ATP021mod"></div>
    
    <script type="text/javascript">
    var myTooltip = new YAHOO.widget.Tooltip("Party_ATP021tip", { 
    context:"Party_ATP021_1", text:"Sozialdemokratische Partei Österreichs 
    (Social Democratic Party of Austria)", showDelay:1000, 
    autodismissdelay:5000,iframe:true, preventoverlap:true } );
    </script>
    SPÖ
    </td>
    
    """
    
    from bs4 import BeautifulSoup
    result_page = BeautifulSoup(html_doc, 'html.parser')
    
    for scrpt in result_page.select("td.headerlast.item script"):
        print(scrpt.next_sibling.strip())
    

    这将导致:

    SPÖ
    

    【讨论】:

    • 您好:我在尝试抓取原本隐藏在“其他”下的部分页面时遇到了同样的问题。尽管有 css 选择,但相同的代码仅适用于最初显示的列。 html_doc='eed.nsd.uib.no/webview/…'
    • Other 下没有脚本标签,因此它不会匹配任何内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-27
    • 2020-11-10
    • 1970-01-01
    相关资源
    最近更新 更多