【发布时间】:2016-12-12 23:20:41
【问题描述】:
这个错误很难描述,因为我无法弄清楚循环是如何影响readline() 和readlines() 方法的。当我尝试使用前者时,我得到了这些意外的 Traceback 错误。当我尝试后者时,我的代码运行并且没有任何反应。我已经确定该错误位于前八行。 Topics.txt 文件的前几行已发布。
Code
import requests
from html.parser import HTMLParser
from bs4 import BeautifulSoup
Url = "https://ritetag.com/best-hashtags-for/"
Topicfilename = "Topics.txt"
Topicfile = open(Topicfilename, 'r')
Line = Topicfile.readlines()
Linenumber = 0
for Line in Topicfile:
Linenumber += 1
print("Reading line", Linenumber)
Topic = Line
Newtopic = Topic.strip("\n").replace(' ', '').replace(',', '')
print(Newtopic)
Link = Url.join(Newtopic)
print(Link)
Sourcecode = requests.get(Link)
当我在此处运行此位时,它会打印以该行的第一个字符开头的 URL。例如,它会打印为 2https://ritetag.com/best-hashtags-for/4https://ritetag。 com/best-hashtags-for/Hhttps://ritetag.com/best-hashtags-for/ 等 24 小时健身。
Topics.txt
- 21 世纪福克斯
- 24 小时健身
- 2K 游戏
- 3M
Full Error
阅读第 1 行 24HourFitness 2https://ritetag.com/best-hashtags-for/4https://ritetag.com/best-hashtags-for/Hhttps://ritetag.com/best-hashtags-for/ohttps://ritetag.com/ best-hashtags-for/uhttps://ritetag.com/best-hashtags-for/rhttps://ritetag.com/best-hashtags-for/Fhttps://ritetag.com/best-hashtags-for/ihttps: //ritetag.com/best-hashtags-for/thttps://ritetag.com/best-hashtags-for/nhttps://ritetag.com/best-hashtags-for/ehttps://ritetag.com/best- hashtags-for/shttps://ritetag.com/best-hashtags-for/s
Traceback(最近一次调用最后一次):文件 "C:\Users\Caden\Desktop\Programs\LususStudios\AutoDealBot\HashtagScanner.py", 第 17 行,在 源代码 = requests.get(Link) 文件 "C:\Python34\lib\site-packages\requests-2.10.0-py3.4.egg\requests\api.py", 第 71 行,在获取 return request('get', url, params=params, **kwargs) 文件 "C:\Python34\lib\site-packages\requests-2.10.0-py3.4.egg\requests\api.py", 第 57 行,应要求提供 返回 session.request(method=method, url=url, **kwargs) 文件 "C:\Python34\lib\site-packages\requests-2.10.0-py3.4.egg\requests\sessions.py", 第 475 行,应要求提供 resp = self.send(prep, **send_kwargs) 文件 "C:\Python34\lib\site-packages\requests-2.10.0-py3.4.egg\requests\sessions.py", 第 579 行,在发送中 适配器 = self.get_adapter(url=request.url) 文件 "C:\Python34\lib\site-packages\requests-2.10.0-py3.4.egg\requests\sessions.py", 第 653 行,在 get_adapter 中 raise InvalidSchema("No connection adapters were found for '%s'" % url) requests.exceptions.InvalidSchema: 没有连接适配器 为 '2https://ritetag.com/best-hashtags-for/4https://ritetag.com/best-hashtags-for/Hhttps://ritetag.com/best-hashtags-for/ohttps://ritetag.com /best-hashtags-for/uhttps://ritetag.com/best-hashtags-for/rhttps://ritetag.com/best-hashtags-for/Fhttps://ritetag.com/best-hashtags-for/ihttps ://ritetag.com/best-hashtags-for/thttps://ritetag.com/best-hashtags-for/nhttps://ritetag.com/best-hashtags-for/ehttps://ritetag.com/best -hashtags-for/shttps://ritetag.com/best-hashtags-for/s'
【问题讨论】:
-
使用
Line = Topicfile.readlines()一次性读取文件。去掉那条线。 -
在底层,readlines 方法“使用”文件,因此当它返回底层文件时,位置指针位于文件末尾。然后你尝试在 for 循环中再读一些文件,但由于它已经在最后,它什么也不做。只使用这两种方法中的一种。
标签: python python-3.x for-loop readlines