【问题标题】:Python Web Scraping IssuePython网页抓取问题
【发布时间】:2016-02-05 01:05:50
【问题描述】:

基本上我有一个大的 html 文档,我想抓取。类似文档的一个非常简化的示例如下:

<a name = 'ID_0'></a>
<span class='c2'>Date</span>
<span class='c2'>December 12,2005</span>
<span class='c2'>Source</span>
<span class='c2'>NY Times</span>
<span class='c2'>Author</span>
<span class='c2'>John</span>

<a name = 'ID_1'></a>
<span class='c2'>Date</span>
<span class='c2'>January 21,2008</span>
<span class='c2'>Source</span>
<span class='c2'>LA Times</span>

<a name = 'ID_2'></a>
<span class='c2'>Source</span>
<span class='c2'>Wall Street Journal</span>
<span class='c2'>Author</span>
<span class='c2'>Jane</span>

该文档大约有 3500 个“a”标签,起初我认为每个标签都有相同的布局。所以,我写了一些类似的东西:

a_list = soup.find_all('a')
data2D = []
for i in range(0,len(a_list)):
    data=[]
    data.append(a_list[i]['name'])
    data.append(a_list[i].find_next(text='Date').find_next().text)
    data.append(a_list[i].find_next(text='Source').find_next().text)
    data.append(a_list[i].find_next(text='Author').find_next().text)
    data2D.append(data)

但是,由于某些 ID 缺少作者或日期,因此抓取工具会从下一个 ID 中获取下一个可用的作者或日期。 ID_1 将具有 ID_2 作者。 ID_2 将具有 ID_3 日期。我的第一个想法是以某种方式跟踪每个标记处的索引,如果索引超过下一个“a”标记索引,则附加 null。有没有更好的解决方案?

【问题讨论】:

  • 使用 lxml 和 xpath..

标签: python html web-scraping beautifulsoup html-parsing


【解决方案1】:

我将使用.find_next_siblings()(或.find_all_next())代替find_next(),并获取所有标签,直到下一个a 链接或文档结尾。大致如下:

links = soup.find_all('a', {"name": True})
data = []
columns = set(['Date', 'Source', 'Author'])

for link in links:
    item = [link["name"]]
    for elm in link.find_next_siblings():
        if elm.name == "a":
            break  # hit the next "a" element - break

        if elm.text in columns:
            item.append(elm.find_next().text)

     data.append(item)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-07
    • 2023-01-07
    • 2021-05-08
    • 2020-07-03
    • 2016-03-14
    相关资源
    最近更新 更多