【问题标题】:Trouble executing my class crawler执行我的班级爬虫时遇到问题
【发布时间】:2017-10-19 16:24:29
【问题描述】:

在使用类抓取任何 Web 数据时,我完全是 python 新手。所以,对于任何严重的错误,请提前道歉。我编写了一个脚本来使用来自维基百科网站的a 标签解析文本。我试图从我的水平上准确地编写代码,但由于某种原因,当我执行代码时它会抛出错误。下面给出了我遇到的代码和错误,以供您考虑。

脚本:

import requests
from lxml.html import fromstring

class TextParser(object):

    def __init__(self):
        self.link = 'https://en.wikipedia.org/wiki/Main_Page'
        self.storage = None

    def fetch_url(self):
        self.storage = requests.get(self.link).text

    def get_text(self):
        root = fromstring(self.storage)
        for post in root.cssselect('a'):
            print(post.text)

item = TextParser()
item.get_text()

错误:

Traceback (most recent call last):
  File "C:\Users\mth\AppData\Local\Programs\Python\Python35-32\testmatch.py", line 38, in <module>
    item.get_text()
  File "C:\Users\mth\AppData\Local\Programs\Python\Python35-32\testmatch.py", line 33, in get_text
    root = fromstring(self.storage)
  File "C:\Users\mth\AppData\Local\Programs\Python\Python35-32\lib\site-packages\lxml\html\__init__.py", line 875, in fromstring
    is_full_html = _looks_like_full_html_unicode(html)
TypeError: expected string or bytes-like object

【问题讨论】:

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


    【解决方案1】:

    你正在执行以下两行

    item = TextParser()
    item.get_text()
    

    当您初始化TextParser 时,self.storage 等于 None。当您执行函数 get_text() 时,它仍然等于 None。所以这就是你得到这个错误的原因。

    但是,如果您将其更改为以下内容。 self.storage 应该填充一个字符串而不是没有。

    item = TextParser()
    item.fetch_url()
    item.get_text()
    

    如果你想调用函数 get_text 而不调用 fetch_url 你可以这样做。

    def get_text(self):
        self.fetch_url()
        root = fromstring(self.storage)
        for post in root.cssselect('a'):
            print(post.text)
    

    【讨论】:

    • 感谢 Jonathan 先生,现在可以使用了。很快就会接受它作为答案。请不要忽略关于如何在不调用fetch_url() 的情况下执行刮板的建议。这是我首先尝试的。谢谢,非常感谢。
    • 嗯,你可以在get_text函数中调用fetch_url。
    • 非常感谢。就是这样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    • 2021-09-11
    • 1970-01-01
    相关资源
    最近更新 更多