簡體   English   中英

Python TypeError:“NoneType”對象不可調用

[英]Python TypeError: 'NoneType' object is not callable

我正在嘗試抓取網站並將數據寫入 CSV 文件(成功)。 我面臨兩個挑戰:

  1. CSV 文件中的數據保存在 ROWS 中而不是列中。
  2. 站點有頁面,1,2,3,4...接下來我無法瀏覽所有頁面來抓取數據。 數據僅從第一頁開始。

錯誤:

if last_link.startswith('Next'):
TypeError: 'NoneType' object is not callable

代碼:

import requests
import csv
from bs4 import BeautifulSoup

url = 'http://localhost:8088/wiki.html'

response = requests.get(url)
html = response.content
soup = BeautifulSoup(html)

table = soup.find('table', {'class' : 'tab_operator'})

list_of_rows = []
for rows in table.findAll('tr'):
    list_of_cells = []
    for cell in rows.findAll('td'):
        list_of_links = []
        for links in cell.findAll('a'):
            text = links.text.replace(' ', '')
            list_of_links.append(text)
        list_of_rows.append(list_of_links)

outfile = open('./outfile.csv', 'w')
writer = csv.writer(outfile)
writer.writerows(list_of_rows)

try:
    last_link = soup.find('table', {'id' : 'str_nav'}).find_all('a')[-1]
    if last_link.startswith('Next'):
        next_url_parts = urllib.parse.urlparse(last_link['href'])
        url = urllib.parse.urlunparse((base_url_parts.scheme, base_url_parts.netloc, next_url_parts.path, next_url_parts.params, next_url_parts.query, next_url_parts.fragment))

except ValueError:
    print("Oops! Try again...")

網站 HTML 示例代碼:

### Numbers to scrape ###

<table cellpadding="10" cellspacing="0" border="0" style="margin-top:20px;" class="tab_operator">
<tbody><tr>
<td valign="top">
<a href="http://localhost:8088/wiki/9400000">9400000</a><br>
<a href="http://localhost:8088/wiki/9400001">9400001</a><br>
</td>
</tr></tbody>
</table>

###  Paging Sample Code: ###

<div class="pstrnav" align="center">
<table cellpadding="0" cellspacing="2" border="0" id="str_nav">
<tbody>
<tr>
<td style="background-color:#f5f5f5;font-weight:bold;">1</td>
<td><a href="http://localhost:8088/wiki/2">2</a></td>
<td><a href="http://localhost:8088/wiki/3">3</a></td>
<td><a href="http://localhost:8088/wiki/4">4</a></td>
<td><a href="http://localhost:8088/wiki/2">Next &gt;&gt;</a></td>
<td><a href="http://localhost:8088/wiki/100">Last</a></td>
</tr>
</tbody>
</table>
</div>

last_link是一個標簽對象,而不是一個字符串。 BeautifulSoup 將標簽上不是現有屬性或方法的任何屬性名稱視為標簽搜索 因為鏈接中沒有startswith標記,該搜索返回None ,並且它是您嘗試調用的對象:

>>> last_link = soup.find('table', {'id' : 'str_nav'}).find_all('a')[-1]
>>> last_link
<a href="http://localhost:8088/wiki/100">Last</a>
>>> last_link.startswith is None
True
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable

您想要測試包含的文本

if last_link.get_text(strip=True).startswith('Next'):

這使用Tag.get_text()方法來訪問鏈接中的所有文本; 即使鏈接中包含其他標簽(如<b><i>標記),使用此方法也能正常工作。

您可能想直接在此處搜索Next鏈接:

import re

table = soup.select_one('table#str_nav')
last_link = table.find('a', text=re.compile('^Next'))

正則表達式指定只有​​直接包含以Next開頭的文本才允許匹配a標簽。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM