【问题标题】:Webscraping with python to extract data使用 python 进行 Web Scraping 以提取数据
【发布时间】:2017-06-28 05:17:11
【问题描述】:

我正在使用以下代码。除了“从属关系”部分外,一切正常。 它返回一个错误: AttributeError:“NoneType”对象没有属性“文本” 如果没有 .text,它会返回所有内容——类中的整个代码

import requests
import bs4
import re

headers = {'User-Agent':'Mozilla/5.0'}

url = 'http://pubs.acs.org/toc/jacsat/139/5'
html = requests.get(url, headers=headers)

soup = bs4.BeautifulSoup(html.text, 'lxml')

tags = soup.findAll('a', href=re.compile("full"))

for tag in tags:
    new_url = tag.get('href', None)
    newurl = 'http://pubs.acs.org' + new_url
    newhtml = requests.get(newurl, headers=headers) 
    newsoup = bs4.BeautifulSoup(newhtml.text, 'lxml')

    article_title = newsoup.find(class_="articleTitle").text
    print(article_title)

    affiliations = newsoup.find(class_="affiliations").text
    print(affiliations)

    authors = newsoup.find(id="authors").text
    print(authors)

    citation_year = newsoup.find(class_="citation_year").text
    print(citation_year)

    citation_volume = newsoup.find(class_="citation_volume").text
    print(citation_volume)

    citation = newsoup.find(id="citation").text
    print(citation)

    pubdate = newsoup.find(id="pubDate").text
    print(pubdate)

【问题讨论】:

    标签: python-3.x web-scraping attributeerror


    【解决方案1】:

    此异常被触发,因为它没有找到具有类“联盟”类的任何元素。 在脚本擦除的第一个URL中,我已经检查了源HTML(或任何其他属性)中具有此类值的任何元素。

    我会捕获错误以避免脚本在找不到元素时禁止返回None或默认字符串。

    那样的东西:

    try:
        affiliations = newsoup.find(class_="affiliations").text
        print(affiliations)
    except AttributeError:
        affiliations = None
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-13
      • 1970-01-01
      • 2017-05-14
      • 2020-01-16
      • 1970-01-01
      • 2014-03-21
      • 2021-08-19
      • 2019-01-31
      相关资源
      最近更新 更多