【问题标题】:web-scraping using python ('NoneType' object is not iterable)使用 python 进行网络抓取('NoneType' 对象不可迭代)
【发布时间】:2018-01-22 06:44:01
【问题描述】:

我是 python 和网络抓取的新手。我正在尝试抓取一个网站(链接是网址)。我收到一个错误,因为“'NoneType' 对象不可迭代”,下面的代码的最后一行。谁能指出哪里出了问题?

import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin

url = 'https://labtestsonline.org/tests-index'
soup = BeautifulSoup(requests.get(url).content, 'lxml')

# Function to get hyper-links for all test components
hyperlinks = []
def parseUrl(url):
    global hyperlinks
    page = requests.get(url).content
    soup = BeautifulSoup(page, 'lxml')
    for a in soup.findAll('div',{'class':'field-content'}):
        a = a.find('a')
        href = urlparse.urljoin(Url,a.get('href'))
        hyperlinks.append(href)



parseUrl(url)

# function to get header and common questions for each test component
def header(url):
    page = requests.get(url).content
    soup = BeautifulSoup(page, 'lxml')
h = []
commonquestions = []
for head in soup.find('div',{'class':'field-item'}).find('h1'):
    heading = head.get_text()
    h.append(heading)
for q in soup.find('div',{'id':'Common_Questions'}):
    questions = q.get_text()
    commonquestions.append(questions)

for i in range(0, len(hyperlinks)):
    header(hyperlinks[i])

以下是回溯错误:

<ipython-input-50-d99e0af6db20> in <module>()
1 for i in range(0, len(hyperlinks)):
2     header(hyperlinks[i])
<ipython-input-49-15ac15f9071e> in header(url)
5     soup = BeautifulSoup(page, 'lxml')
6     h = []
for head in soup.find('div',{'class':'field-item'}).find('h1'):
heading = head.get_text()
h.append(heading)
TypeError: 'NoneType' object is not iterable

【问题讨论】:

  • 您在哪一行出现错误?
  • 请将完整错误回溯添加到您的问题中!
  • @VikasDamodar 最后一行,即 for 循环
  • 你可以检查你的代码缩进并进行更改吗?
  • @VikasDamodar 我添加了错误回溯

标签: python web-scraping beautifulsoup


【解决方案1】:

soup.find('div',{'class':'field-item'}).find('h1') 正在返回 None。在循环之前首先检查函数是否返回任何内容。

类似:

heads = soup.find('div',{'class':'field-item'}).find('h1')
if heads:
    for head in heads:
        # remaining code

【讨论】:

  • 我已经按照你的建议做了。它抛出了这个错误:AttributeError: 'NavigableString' object has no attribute 'get_text'
【解决方案2】:

试试这个。它应该可以解决您目前遇到的问题。我使用 css 选择器来完成工作。

import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin

link = 'https://labtestsonline.org/tests-index'
page = requests.get(link)
soup = BeautifulSoup(page.content, 'lxml')
for a in soup.select('.field-content a'):
    new_link = urljoin(link,a.get('href'))   ##joining broken urls so as to reuse these
    response = requests.get(new_link)        ##sending another http requests
    sauce = BeautifulSoup(response.text,'lxml')
    for item in sauce.select("#Common_Questions .field-item"):
        print(item.text)
    print("<<<<<<<<<>>>>>>>>>>>")

【讨论】:

    猜你喜欢
    • 2020-07-17
    • 2019-11-30
    • 1970-01-01
    • 2013-12-01
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多