python - 在 BeautifulSoup 中打印和格式化结果

标签 python string beautifulsoup

我的问题是我只想打印带有“1”的结果,而不是“-1”,但是当我使用 find() 时,我只得到“1”或“-1” 。我知道这是有效的,但是有没有什么函数可以只用“1”打印这个,而不是数字而是整行?

import requests
import bs4

def links(url):
    response = requests.get(url)
    soup = bs4.BeautifulSoup(response.text)
    tmp = soup.find_all('a')

    for links in tmp:
        print(links.get('href'),  links.get('href').find("torrent_download"))


url="http://extratorrent.cc"
print(links(url))

结果示例:

/category/23/zzz.html -1

/torrent_download/4188694/zzz.torrent 1

/torrent/4188694/zzz.html#comments -1

/torrent_download/4188710/zzz.torrent 1

我想要的结果:

/torrent_download/4188710/zzz.torrent 1
/torrent_download/4188694/zzz.torrent 1

最佳答案

在打印之前检查 get.find:

for links in tmp:
    get  =  links.get('href').find("torrent_download")
    if get != -1:
        print(links.get('href'),  get)

关于python - 在 BeautifulSoup 中打印和格式化结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30203245/

相关文章:

java - 我在扫描字符串时遇到问题

android - Android中能否从strings.xml以外的资源文件中加载字符串资源?

c++ - 如何在 C++ 中的日文字符串中查找空格?

python - 用 Beautiful Soup 提取 href

python - 通过 Mechanize 绕过 404

python - 使 python 脚本在 x 秒不活动后退出

python - 在 matplotlib 中同时更改线宽和颜色

python - 如何在 python 上循环而不出现 IndexError ?

python - 如何输入提示返回作为参数传递的类实例并具有默认值的方法?

python - 在 python 中抓取表