首页 > 解决方案 > 抓取网站来源并搜索单词

问题描述

我有这个 Python 代码,但它搜索实际页面而不是页面的

import requests
from bs4 import BeautifulSoup

def count_words(url, the_word):
    r = requests.get(url, allow_redirects=False)
    soup = BeautifulSoup(r.content, 'lxml')
    words = soup.find(text=lambda text: text and the_word in text)
    print(words)
    return len(words)


def main():
    url = 'google.com'
    word = 'google'
    count = count_words(url, word)
    print('\nUrl: {}\ncontains {} occurrences of word: {}'.format(url, count, word))

if __name__ == '__main__':
    main()

我如何让它也搜索页面的来源?

我不想数。是的,我知道我必须删除该count {}部分。但是,如何让它从文本文件中加载网站列表,如果找到 x 单词打印“X Found on this website”

任何帮助表示赞赏!

标签: pythonhtmlbeautifulsoup

解决方案


如果要在源代码中搜索某个子字符串的出现情况,则无需使用 BeautifulSoup。它只会让您解析实际的页面内容,而不包括源代码。

替换count_words()为以下代码。

def count_words(url, the_word):
    r = requests.get(url).text    
    return r.count(the_word)

Output (do NOT include this in the final code):
>>> count_words('https://google.com', 'Google')
8

您只需要使用 将网页源代码作为字符串获取requests,并使用 计算子字符串的出现次数.count()

此外,请确保在 URL 中添加方案(例如http, )。https否则,BeautifulSoup 会“吓坏”。


推荐阅读