python - 在一组网页问题中查找特定单词
问题描述
此代码获取 udacity 网站中的课程链接并搜索每个链接以找到搜索词(“计算机视觉”)。如果找到搜索,它将打印该链接。但在我的代码中,它也会打印不包含搜索词的链接。对于其他一些搜索词(例如:python),它会省略一些包含搜索词的 url。可能是什么原因。
例如没有搜索词的链接: https ://in.udacity.com/course/advanced-android-app-development--ud855
https://in.udacity.com/course/engagement-monetization-mobile-games--ud407 等。
import requests
from bs4 import BeautifulSoup
import re
from urllib.parse import urlencode
from urllib.request import urlopen
page = requests.get("https://in.udacity.com/courses/all")
soup = BeautifulSoup(page.content, 'html.parser')
courses = soup.find_all("a",class_='capitalize')
search_term = "computer vision"
i=1
for link in courses:
site =urlopen("https://in.udacity.com"+link.get("href")).read()
if search_term in site.decode():
print("https://in.udacity.com"+link.get("href"))
解决方案
我认为这个问题的原因是因为 JavaScript 代码包含search_term
.
您可以尝试替换urlopen().read().decode()
为requests.get().text
.
site =urlopen("https://in.udacity.com"+link.get("href")).read()
if search_term in site.decode():
print("https://in.udacity.com"+link.get("href"))
# to
site = requests.get("https://in.udacity.com"+link.get("href"))
if search_term in site.text:
print("https://in.udacity.com"+link.get("href"))
requests.get().text
只包含在浏览器上显示的字符。
推荐阅读
- typescript - 如何使用泛型访问 typeof 类
- c# - 在 C# 中使用信号量和超时异步调用 WebMethod
- c# - 在 WPF 应用程序中显示另一个应用程序的窗口
- linux - 如何将主机目录挂载到我的非特权 lxc
- python - 向 Pytorch Dataloader 添加类对象:批处理必须包含张量
- sql - Postgresql - 分组依据
- amcharts4 - 在amcharts甘特图中绘制一条表示当前日期的移动垂直线?
- amazon-web-services - 如何在 ansible-playbook 中查找 amazon.aws.aws_secret?
- reactjs - 主对象可能未定义时的双重解构
- python - 错误:ModuleNotFoundError:没有名为“tensorflow.contrib”的模块