【问题标题】:Extract links from a webpage and create a dictionary Python从网页中提取链接并创建字典 Python
【发布时间】:2016-06-03 22:29:21
【问题描述】:

编写一个函数来打开一个网页并返回该页面上所有链接及其文本的字典。链接是字典键,文本是字典值。

这是我目前所拥有的。

import urllib.request as urlrequest
def getLinks(url):

   page=urlrequest.urlopen(url)

   lines = page.readlines()


   url_list={}
   for line in lines:
      if '<a href=' in line:
          removeHref=line[8:]
          end=removeHref.find('>')
          url=removeHref[0:end]
          removeHref=removeHref[end+1:]
          print (url)
          end2=removeHref.find('<')
          text=removeHref[0:end2]
          print ('%s \n' % text)
          url_list[url] = text



url = input("URL: ")
getLinks(url)

但是当我输入一个链接并运行它时,它给了我以下错误:

 if '<a href=' in line:
 TypeError: a bytes-like object is required, not 'str'

我该如何解决这个问题?

【问题讨论】:

  • 你试过用双引号吗?另外,您使用的是哪个 python 版本,对我来说可以正常工作

标签: python http url


【解决方案1】:

您无法检查stringbyte 之间的遏制,它必须是bytebytestringstring

因为您的网页是作为 byte 对象返回的。你应该这样做:

if b'<a href=' in line:
     pass # your code here

【讨论】:

    猜你喜欢
    • 2019-04-12
    • 2011-07-04
    • 2020-04-27
    • 1970-01-01
    • 2012-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多