python - 查找字符串中不存在的文本

标签 python string text

如您所见,我定义了两个变量:一个名为 href 的变量,它有多个链接作为一个字符串;另一个名为 text 的变量,现在位于 text 中 我有我已经访问过/下载过的链接。我希望 Python 打印 href 中存在的文本,但 text 中不存在的文本。

所以我想象它使用 for 循环?

当我执行单个字母时,会返回单个字母,所有字母都在不同的行上分隔。

import requests
from bs4 import BeautifulSoup

url = 'amazon.com'
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, 'html.parser')

for link in soup.findAll('a', {'class': 'gridItem-trackInfo-title-anchor'}):
    href = link.get('href')

    file = open('file.txt', 'r')
    text = file.read()
    file.close

    for i in href:
        if i not in text:
            print(i)

最佳答案

如果您只想在一行上输入,请使用 print(i, end='') 就可以了。

<小时/>

如果你想要链接,你应该这样做

for i in links(href):
    if i not in links(text):
        print(i)

可以在retrieve links from web page using python and BeautifulSoup找到links功能。

<小时/>

如果您想要链接而不是字母,请使用:

    if link not in text:
        print(link)

在循环每个链接的字母之前。

而不是:

for i in href:
    if i not in text:
        print(i)

关于python - 查找字符串中不存在的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34384192/

相关文章:

javascript - 如何构建网页文件浏览器?

arrays - 区分字符串中的数字

java - 在 Java 中将文本文件转换为数组

javascript - 获取文本选择的每一行

python - 如何找到其他两个列表中的每个元素?

python - 如何使用python将多个json对象合并为一个json对象

python - 如何在python中同时运行两个同步进程

c - 如何用C语言将两个字符串写入一个文件并对其进行排序?

c - 使用 regex.h 在 c 中进行模式匹配/提取

linux - 如何使用 bash 加入两个文件并删除重复项?