python - 抓取网站来源并搜索单词
问题描述
我有这个 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”
任何帮助表示赞赏!
解决方案
如果要在源代码中搜索某个子字符串的出现情况,则无需使用 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 会“吓坏”。
推荐阅读
- java - Netty HttpStaticFileServerHandler 问题
- list - F# list.fold 最大值
- python - 如何在 Pandas 中将字典值解压缩到 DataFrame
- macos - 用于编辑多个文本文件的 Bash 脚本
- sql - 在 CASE 表达式的 ELSE 中组合多行
- vue.js - Nuxt.js 并处理动态页面的 API 404 响应
- c# - 使 Windows 上的第 3 方程序相信 HID 设备已连接
- python - 正则表达式 - 在文本中搜索相似的国家名称
- python - 如何打磨 ttk.Treeview 子节点中的值
- c# - 引用被引用的 DLL 所需的 DLL 应该是哪个项目的责任?