【问题标题】:How can I address this error: InvalidSchema("No connection adapters were found for {!r}".format(url))?如何解决此错误:InvalidSchema("No connection adapters were found for {!r}".format(url))?
【发布时间】:2020-09-03 12:33:54
【问题描述】:

我收到此错误: InvalidSchema("没有为 {!r} 找到连接适配器".format(url))

当我尝试运行这段代码时:

import pandas as pd
pd.set_option('display.max_colwidth', -1)
url_file = 'https://github.com/MarissaFosse/ryersoncapstone/raw/master/DailyNewsArticles.xlsx'

tstar_articles = pd.read_excel(url_file, "TorontoStar Articles", header=0) 

url_to_sents = {}

for url in tstar_articles:
  url = tstar_articles['URL']
  page = requests.get(url)
  soup = BeautifulSoup(page.content, 'html.parser')
  results = soup.find(class_='c-article-body__content') 
  results_text = [tag.get_text().strip() for tag in results]
  sentence_list = [sentence for sentence in results_text if not '\n' in sentence]
  sentence_list = [sentence for sentence in sentence_list if '.' in sentence]
  article = ' '.join(sentence_list)
  url_to_sents[url] = article

我正在尝试使用 requests() 从我创建的 Excel 文件中读取 URL。我怀疑这是由于看不见的字符,但不知道如何检查。

【问题讨论】:

  • 不要从堆栈跟踪中粘贴创建异常的代码行,而是向我们提供异常本身的文本。 (包括整个堆栈跟踪通常也是很好的做法)。

标签: python pandas url beautifulsoup python-requests


【解决方案1】:

当您遍历返回的数据框时,它只返回列名。因此,您的原始代码首先将Date 分配给url,然后是Category,以此类推;这些字符串没有 URL,因此出现错误。

相比之下,查找数据框中的任何列都会返回一个可以迭代的序列。因此,不要在需要 URL 时迭代 tstar_articles,而是迭代 tstar_articles['URL']

因此,而不是:

for url in tstar_articles:
    url = tstar_articles['URL']
    page = requests.get(url)

...使用:

for url in tstar_articles['URL']:
    page = requests.get(url) 

【讨论】:

  • 修改为包含解释而不是裸代码。 @MarissaFosse,考虑单击答案旁边的复选框以标记您的问题已解决。
猜你喜欢
  • 2022-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-19
  • 2012-12-18
相关资源
最近更新 更多