ValueError:只能解析字符串python

时间:2015-10-19 22:43:29

标签: python lxml screen-scraping

我正在尝试使用xpath收集一堆链接,需要从下一页抓取但是,我一直得到只能解析字符串的错误?我试着看看lk的类型,在我投入之后它是一个字符串?什么似乎是错的?

 def unicode_to_string(types):
   try:
      types = unicodedata.normalize("NFKD", types).encode('ascii', 'ignore')
      return types
  except:
      return types

def getData():
  req = "http://analytical360.com/access-points"
  page = urllib2.urlopen(req)
  tree = etree.HTML(page.read())  
  i = 0
   for lk in tree.xpath('//a[@class="sabai-file sabai-file-image sabai-file-type-jpg "]//@href'):
      print "Scraping Vendor #" + str(i)
      trees = etree.HTML(urllib2.urlopen(unicode_to_string(lk))) 
      for ll in trees.xpath('//table[@id="archived"]//tr//td//a//@href'):
         final = etree.HTML(urllib2.urlopen(unicode_to_string(ll)))

1 个答案:

答案 0 :(得分:1)

你应该传入字符串而不是urllib2.orlopen。

也许更改代码如下:

trees = etree.HTML(urllib2.urlopen(unicode_to_string(lk)).read()) 
    for i, ll in enumerate(trees.xpath('//table[@id="archived"]//tr//td//a//@href')):
        final = etree.HTML(urllib2.urlopen(unicode_to_string(ll)).read())

此外,您似乎没有增加i