【发布时间】: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