首页 > 解决方案 > 在一组网页问题中查找特定单词

问题描述

此代码获取 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"))

标签: pythonweb-scraping

解决方案


我认为这个问题的原因是因为 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只包含在浏览器上显示的字符。


推荐阅读