【问题标题】:Parsing a list of urls in python解析python中的url列表
【发布时间】:2018-03-10 19:00:53
【问题描述】:

我正在尝试使用 urlopen 从列表中的每个 url 获取一些文本。但是,urllib 似乎无法将列表中的每个 url 作为字符串读取并不断返回此错误:

AttributeError: 'list' object has no attribute 'timeout'

当我尝试在循环中将每个列表对象转换为字符串时,它仍然无法读取:

URLError: urlopen error unknown url type: ['https>

我的代码如下所示:

for url in urls:
    str_url = str(url)
    page = urlopen(str_url).read()
    soup = bs(page)

这些值来自一个 csv 文件,其中每个 url 都是一行。在循环中打印时,它看起来像这样:

['premierleague.com/players/3861/player/overview#'] ['premierleague.com/players/2537/player/overview#'] ...等等

【问题讨论】:

  • 你能提供urls的内容和实际的stacktrace吗?
  • 我能够模拟这个 SO。列表 urls 位于列表中,因此它会中断,例如:[[url]]。向我们展示 url 的示例值,然后我们将提供帮助。
  • 这些值来自一个 csv 文件,其中每个 url 都是一行。在循环中打印时,它看起来像这样: ['premierleague.com/players/3861/player/overview#'] ['premierleague.com/players/2537/player/overview#'] ...等等
  • 尝试获取数组列表中每个数组的第一个值。这将是一个 urlopen 知道如何处理的字符串
  • 您的 CSV 中的某个网址似乎有错字,例如https> 而不是 https://,请尝试添加 print url,以便查看哪些 URL 导致了问题。

标签: python urlopen


【解决方案1】:

假设每一行只包含一个 url 字符串。然后你可以使用文件对象来读取每一行,这会返回一个字符串。

from urllib.request import urlopen

for url in open('your_url_list.csv', 'r'):
    url = 'http://' + url if 'http' not in url else url
    source = urlopen(url).read()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-15
    • 1970-01-01
    相关资源
    最近更新 更多