【问题标题】:python 'NoneType' object has no attribute 'decompose'python 'NoneType' 对象没有属性 'decompose'
【发布时间】:2018-05-25 18:14:59
【问题描述】:
from bs4 import BeautifulSoup
import time
#import requests
import urllib.request,re
#import pandas as pd
#import numpy as np
import csv

def crawlcontents():
    url = 'https://www.tripadvisor.com/ShowTopic-g983296-i13236-k11538516-Rent_from_LOTTE_standard_or_mystery_option-Jeju_Island.html' 

    html = urllib.request.urlopen(url).read().decode() 

#    print(html)

    soup = BeautifulSoup(html,'html.parser')
#    print(soup)
    div = soup.select_one('#SHOW_TOPIC > div.balance > div.firstPostBox > div > div > div.postRightContent > div.postcontent > div.postBody')
    div.select_one('script').decompose() 

    postcontent = div.text.strip()
    postcontent = re.sub(r'\n+', ' ',postcontent)
    print(postcontent)

crawlcontents()

这是在旅行网站上爬行。 我需要一个脚本,但错误是:

python 'NoneType' 对象没有属性 'decompose'

我该如何改变呢?

【问题讨论】:

  • 你为什么大喊大叫?你得到的实际回溯是什么?
  • 您能解释一下调用.decompose() 的那一行想要完成什么吗? div 变量不包含任何 script CSS 选择器,因此当您尝试使用 select_one 选择它时,它会返回 None,因此会出现错误。

标签: python html web web-scraping web-crawler


【解决方案1】:

我假设你想要“神秘选项似乎有很大的价格优惠 - 但你不知道你会得到什么车你会坐哪一辆?结果会好吗?”作为输出对吗?您正在尝试使用分解来删除标签,但这不是必需的。

如果这是您想要的输出,“div”就是一个结果集。我不认为你可以再次运行 select_one 。在这种情况下,您甚至不需要 re 。试试这个:

#Remove the below
div.select_one('script').decompose()

#Include the below
postcontent = div[0].text.strip().replace('\n',' ')

您必须使用元素 div[0] 而不是结果集 div。 strip() 删除末尾的空格,而 replace 删除两个注释字符串之间的空格。

【讨论】:

    猜你喜欢
    • 2013-04-19
    • 2019-10-03
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    相关资源
    最近更新 更多