【问题标题】:Python: Attempting to find a word in a string from HTTPRequestPython:尝试在 HTTPRequest 的字符串中查找单词
【发布时间】:2021-01-07 15:55:59
【问题描述】:

我正在尝试寻找一种方法来搜索网页的源代码以查看它是否包含关键字。但是,无论我在此页面上搜索什么,我得到的唯一结果是 -1,我认为这告诉我我做错了什么。否则,我认为它应该告诉我单词开始的位置。有人可以告诉我我做错了什么吗?这是代码。

import urllib.request
page = urllib.request.urlopen("http://www.google.com")
print(page.read())

str_page = str(page)

substring = "content"

print(str_page.find("lang"))

【问题讨论】:

  • page 是 url 请求对象 -- 它不是页面 content。您可以使用 page.read() 获取页面内容,但您没有将其保存到变量中。
  • @JohnGordon 足够回答,不是吗?

标签: python html string find httprequest


【解决方案1】:
import urllib2

webUrl  = urllib.request.urlopen('https://www.youtube.com/user/guru99com')
print ("result code: " + str(webUrl.getcode()))
data = webUrl.read()
Source_text = (data)
Keyword = 'your keyword'
if Keyword in Source_text: 
     #put whatever you want here


【讨论】:

    【解决方案2】:

    请查看下面提到的代码是否有帮助

    import urllib.request
    
    url = "http://www.google.com"
    
    response = urllib.request.urlopen(url)
    
    html = response.read().decode('utf-8','ignore')  # decode the html page here 
    if 'lang' in html:
        print (html.find("lang"))  # gives the position of lang
    

    请 decode() html 页面可能会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-28
      • 1970-01-01
      • 2015-12-05
      • 2018-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多