找不到python html解析器数据

时间:2017-08-14 10:14:03

标签: python html parsing web-scraping python-requests

所以我正在制作一个网页“抓取工具”来解析网页,然后在网页中搜索一个单词或一组单词。这就产生了我的问题,我正在寻找的数据包含在已解析的网页中(我使用特定的单词作为测试运行),但它表示找不到它正在寻找的数据。

from html.parser import HTMLParser
from urllib import *

class dataFinder(HTMLParser):
    def open_webpage(self):
        import urllib.request
        request = urllib.request.Request('https://www.summet.com/dmsi/html/readingTheWeb.html')#Insert Webpage
        response = urllib.request .urlopen(request)
        web_page = response.read()
        self.webpage_text = web_page.decode()
        return self.webpage_text


    def handle_data(self, data):
        wordtofind = 'PaperBackSwap.com'
        if data == wordtofind:
            print('Match found:',data)
        else:
            print('No matches found')



p = dataFinder()
print(p.open_webpage())
p.handle_data(p.webpage_text)

我使用feed方法在没有开放网页功能的情况下运行程序,它可以正常工作并找到数据,但它现在无效。

赞赏解决此问题的任何帮助

3 个答案:

答案 0 :(得分:1)

你正在尝试比较html页面和字符串,当然它们不是simillar所以你得到'找不到匹配'。要在字符串中查找字符串,可以使用str.find()方法。它返回文本的第一个找到位置的位置,否则为-1。

正确的代码:

from html.parser import HTMLParser
from urllib import *

class dataFinder(HTMLParser):
    def open_webpage(self):
        import urllib.request
        request = urllib.request.Request('https://www.summet.com/dmsi/html/readingTheWeb.html')#Insert Webpage
        response = urllib.request .urlopen(request)
        web_page = response.read()
        self.webpage_text = web_page.decode()
        return self.webpage_text

    def handle_data(self, data):
        wordtofind = 'PaperBackSwap.com'
        if data.find(wordtofind) != -1:
            print('Match found position:', data.find(wordtofind))
        else:
            print('No matches found')

p = dataFinder()
print(p.open_webpage())
p.handle_data(p.webpage_text)

答案 1 :(得分:0)

我可以使用Beautifulsoup从html内容中解析和查找文本,请查看它是否适合您。以下是您案例的示例代码。

from bs4 import BeautifulSoup

soup= BeautifulSoup(web_page,'html.parser')
for s in soup.findAll(wordtofind):
    if data == wordtofind:
        print('Match found:',data)
    else:
        print('No matches found')

答案 2 :(得分:0)