python - 使用 beautifulsoup4 缺失单元格进行表抓取

标签 python web-scraping beautifulsoup

我在 BS4 中遇到了一些奇怪的行为。我已经复制了我将要抓取的网站的 20 个页面,并且此代码在我的私有(private)网络服务器上运行得非常好。当我在真实站点上使用它时,它会随机丢失一行的第 8 列。我以前没有遇到过这种情况,而且我似乎找不到任何其他有关此问题的帖子。第 8 列是“频率_排名”。这是怎么回事,这只发生在最后一列,我该如何解决?

import requests
import json
from bs4 import BeautifulSoup

base_url = 'http://hanzidb.org'


def soup_the_page(page_number):
    url = base_url + '/character-list/by-frequency?page=' + str(page_number)    
    response = requests.get(url, timeout=5)
    soup = BeautifulSoup(response.content, 'html.parser')
    return soup


def get_max_page(soup):
    paging = soup.find_all("p", {'class': 'rigi'})
    # Isolate the first paging link
    paging_link = paging[0].find_all('a')
    # Extract the last page number of the series
    max_page_num = int([item.get('href').split('=')[-1] for item in paging_link][-1])
    return max_page_num


def crawl_hanzidb():
    result = {}

    # Get the page scrape data
    page_content = soup_the_page(1)
    # Get the page number of the last page
    last_page = get_max_page(page_content)
    # Get the table data
    for p in range(1, last_page + 1):
        page_content = soup_the_page(p)
        for trow in page_content.find_all('tr')[1:]:
            char_dict = {}
            i = 0
            # Set the character as the dict key
            character = trow.contents[0].text
            # Initialize list on dict key
            result[character] = []
            # Return list of strings from trow.children to parse urls
            for tcell in trow.children:
                char_position = 0
                radical_position = 3
                if i == char_position or i == radical_position:
                    for content in tcell.children:
                        if type(content).__name__ == 'Tag':
                            if 'href' in content.attrs:
                                url = base_url + content.attrs.get('href')
                                if i == char_position:
                                    char_dict['char_url'] = url
                                if i == radical_position:
                                    char_dict['radical_url'] = url
                i += 1
            char_dict['radical'] = trow.contents[3].text[:1]
            char_dict['pinyin'] = trow.contents[1].text
            char_dict['definition'] = trow.contents[2].text
            char_dict['hsk_level'] = trow.contents[5].text[:1] if trow.contents[5].text[:1].isdigit() else ''
            char_dict['frequency_rank'] = trow.contents[7].text if trow.contents[7].text.isdigit() else ''
            result[character].append(char_dict)
        print('Progress: ' + str(p) + '%.')
    return(result)


crawl_data = crawl_hanzidb()
with open('hanzidb.json', 'w') as f:
    json.dump(crawl_data, f, indent=2, ensure_ascii=False)

最佳答案

问题似乎是该网站的 HTML 格式不正确。如果你查看你发布的网站的来源,有两个关闭</td>频率排名列之前的标签。示例:

<tr>
    <td><a href="/character/的">的</a></td>
    <td>de</td><td><span class="smmr">possessive, adjectival suffix</span></td>
    <td><a href="/character/白" title="Kangxi radical 106">白</a>&nbsp;106.3</td>
    <td>8</td><td>1</td>
    <td>1155</td></td>
    <td>1</td>
 </tr>

我认为这会导致您正在使用的解析器出现问题( html.parser )。如果您安装lxml解析器,它似乎可以工作。

试试这个:

首先,安装 lxml解析器...

pip install lxml

然后,更改 soup_the_page() 中的解析器方法:

soup = BeautifulSoup(response.content, 'lxml')

然后运行您的脚本。似乎有效。 print(trow.contents[7].text)不再给出索引超出范围的错误。

关于python - 使用 beautifulsoup4 缺失单元格进行表抓取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54606008/

相关文章:

javascript - jQuery 从第一个表中选择三个相同的行中的所有行

python - 无法限制我的脚本解析网页中的特定部分

python - 如何在不达到递归限制的情况下 pickle 具有子对象或邻居关系的 class() 对象并在加载时保留对象

python - 属性错误: 'list' object has no attribute 'dropna' (outlier)

python - 为什么模块在另一个模块中作为 _<name> 导入?

javascript - 从页面抓取时遇到问题

python - 如何在选择器中使用部分文本而不是精确文本?

python - 如何使用 Python 找出我的微调模型?

python - 在 bs4 中使用 .text 时未获取 json

javascript - 逆转网页上 CSS 样式的缩小/混淆