Python分割字符串索引超出范围

标签 python html-parsing

我正在尝试拆分以下标签:

<h3><a href="#AC Adapter" onclick="getProductsBasedOnCategoryID('Asus','AC Adapter','ET1611PUT','6941', this, 'E Series')">AC Adapter

            </a></h3>

使用以下代码:

print "FETCHING CATEGORY"
    atag = s.h3
    for data in atag:
        while getattr(atag, 'name', None) != 'h3':
            atag = atag.nextSibling
        atag.a
        atag = literal_eval('(' + atag.nextSibling.replace(', this', '').split('(', 1)[1])
        print atag

但是,我收到以下错误:

File "//CPSBS/RedirectedFolders/aysha/My Documents/asus_tables(edited) a tags.py", line 84, in <module>
    atag = literal_eval('(' + atag.nextSibling.replace(', this', '').split('(', 1)[1])
IndexError: list index out of range

我猜我做错了什么?另外,这个 a 标签有一个 onclick 属性,我想访问它,那么我如何将其输入到以下代码中?

这是我正在解析数据的网址

http://www.asusparts.eu/partfinder/Asus/All One/E 系列

[编辑]

我正在尝试从中检索数据的导航树

<div id="accordion" class="ui-accordion ui-widget ui-helper-reset ui-accordion-icons" style="width: 760px;" role="tablist"> 
    <h3 class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-top" role="tab" aria-expanded="true" aria-selected="true" tabindex="0"> 
        <span class="ui-icon ui-icon-triangle-1-s"></span> 
        <a onclick="getProductsBasedOnCategoryID('Asus','AC Adapter','ET10B','6941', this, 'E Series')" href="#AC Adapter" tabindex="-1" loaded="Loaded">AC Adapter </a> 
    </h3> 
    <div id="6941" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active" role="tabpanel" style="display: block;"> 
        <table class="productTableList"> 
            <tbody> 
        </table> 
        <table class="productTableList"> 
            <tbody> 
                <tr style="height:90px;background-color:#ebf4ff;"> 
                    <td class="ProduktLista" width="70px"> 
                    <td class="ProduktLista" width="315"> 
                        <a onclick="getProductInformationModal("Asus","14G110008340");"> 
                        <br>  

最佳答案

当你面对这类问题时,你无法立即看出问题是什么,那么你需要将复杂的表达式进行划分。而不是:

atag = literal_eval('(' + atag.nextSibling.replace(', this', '').split('(', 1)[1])

将其重写为(当然,您应该使用更有意义的变量名称):

nextSibling = atag.nextSibling
txt1 = nextSibling.replace(', this', '')
split = txt1.split('(', 1)
txt2 = split[1]
txt3 = '(' + txt2
atag = literal_eval(txt3)

这将为您提供问题存在的确切表达式,并且所涉及值的打印语句应该为您提供答案。

关于Python分割字符串索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16232285/

相关文章:

python - 检测协程是否需要异步循环

python - Jinja2:如何在包含的模板、可扩展模板中使用命名 block

python - 具有稀疏矩阵的 numpy 元素外积

java - 用于短语和区分大小写搜索的 HTML 解析器,使用 Java

c# - 如何从 XML 文件中的位置获取文本?

python - 无法安装最新版本的 pandas (1.0.3)

python - __abstractmethods__ 和 AttributeError

python - Python 中最宽容的 HTML 解析器是什么?

python - 使用 beautifulsoup 从 HTML 获取链接文本

c# - 使每个 block 内的更改持久化