python - 在 beautifulsoup 中编写干净的代码

标签 python beautifulsoup

在解析语义结构很少的网页上的表格时,我 BeautifulSoup 表达式变得非常难看。我可能会以错误的方式处理它,并且想知道如何重写我的代码以使其更具可读性且不那么困惑?

例如,一个页面中有三个表。相关数据见第三表。实际数据从第二行开始。该行中的第一个条目是索引,我需要的数据位于第二个 td 元素中。第二个 td 元素有两个链接,我感兴趣的文本位于第二个 a 标记内。将其翻译成我写的beautifulsoup

soup.find_all('table')[2].find_all('tr')[2].find_all('td')[1].find_all('a')[1].text

工作正常,我在列表理解中使用相同的原理获取表中的所有 70 个元素。

relevant_data = [ x.find_all('td')[1].find_all('a')[1].text for x in soup.find_all('table')[2].find_all('tr')[2:]]

这种代码可以吗?还有改进的余地吗?

最佳答案

使用lxml ,您可以使用XPath。

例如:

html = '''
<body>
    <table></table>
    <table></table>
    <table>
        <tr></tr>
        <tr></tr>
        <tr><td></td><td><a>blah1</a><a>blah1-1</a></td></tr>
        <tr><td></td><td><a>blah2</a><a>blah2-1</a></td></tr>
        <tr><td></td><td><a>blah3</a><a>blah3-1</a></td></tr>
        <tr><td></td><td><a>blah4</a><a>blah4-1</a></td></tr>
        <tr><td></td><td><a>blah5</a><a>blah5-1</a></td></tr>
    </table>
    <table></table>
</body>
'''


import lxml.html
root = lxml.html.fromstring(html)
print(root.xpath('.//table[3]/tr[position()>=2]/td[2]/a[2]/text()'))

输出:

['blah1-1', 'blah2-1', 'blah3-1', 'blah4-1', 'blah5-1']

关于python - 在 beautifulsoup 中编写干净的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21374751/

相关文章:

html - 当多个div具有相同的类名但没有id标签时,如何使用BeautifulSoup选择特定的div?

Python 从 URL 中抓取 YouTube 标题太慢 - html-render

python - 使用 python 对 beautifulsoup 标签列表进行排序

python - Matplotlib 在刻度标签(字符串)中显示美元符号

python - Python 2.6 之前版本中 urllib2.urlopen() 的超时

python - 如何使用 docplex (python) 对优化问题中的约束进行建模?

python - 使用 BeautifulSoup 获取结果集中 td 标签的文本

python - python中for行的语法错误

python - 使用 Pandas Python 将 Dataframe 的列从类型对象转换为 int/float

python - 使用 Selenium 从分类为列表框的按钮中选择值