首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >无法将current_url与Python和Selenium中的列表进行比较

无法将current_url与Python和Selenium中的列表进行比较
EN

Stack Overflow用户
提问于 2018-07-16 03:49:39
回答 1查看 46关注 0票数 1

如果current_url已经在列表中,我会尝试跳过它,但会遇到一条错误消息。

我的目标是抓取一个页面,将该网页添加到文本文件中,然后当我重新开始抓取时,我希望将要抓取的网页与列表中的网页进行比较。当网页在中时,我想跳过它。

但是这个问题突然出现,它无法将current_url与列表进行比较:这段代码:

代码语言:javascript
复制
if cur_url in visited_urls:

完整代码:

打开文本文件

代码语言:javascript
复制
visited_urls = 'C:/webdrivers/visited_p_urls_test.txt' # This specific the location of the text file on the PC
cur_url = driver.current_url

# Go to main test website
driver.get('https://www.google.com')
sleep(randint(1,3))

with open(visited_urls, 'a') as filehandle: # This opens a text file with the "Append to (add) mode."
    filehandle.write('\n' + cur_url)

# Go to main test website
driver.get('https://adwords.google.com/home/')
sleep(randint(1,3))

with open(visited_urls, 'a') as filehandle: # This opens a text file with the "Append to (add) mode."
    filehandle.write('\n' + cur_url)

driver.get('https://adwords.google.com/home/tools/')
sleep(randint(1,3))

with open(visited_urls, 'a') as filehandle: # This opens a text file with the "Append to (add) mode."
    filehandle.write('\n' + cur_url)

if cur_url in visited_urls:
    print 'I CANNOT comment because I already did before' 
else:
    print 'I can comment'

with open(visited_urls, 'r') as filehandle: # This opens a text file with the "Read" mode.
    filecontent = filehandle.readlines()    # readlines reads ALL lines in a text file
    for line in filecontent:
        print(line)

我收到这个错误消息:

代码语言:javascript
复制
TypeError: 'str' object is not callable
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-16 04:00:52

您正在尝试搜索文件路径(C:/webdrivers/visited_p_urls_test.txt)中的字符串,但您必须搜索文件内容:

代码语言:javascript
复制
if 'blabla' in open('example.txt').read():
    print("true")

在您的案例中:

代码语言:javascript
复制
# open file, read it's content and only then search if cur_url exists already in a file
if cur_url in open(visited_urls).read():
    print 'I CANNOT comment because I already did before' 
else:
    print 'I can comment'
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51351713

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档