Using BeautifulSoup to search html for string

后端 未结 4 1293
予麋鹿
予麋鹿 2020-11-30 01:20

I am using BeautifulSoup to look for user entered strings on a specific page. For example, I want to see if the string \'Python\' is located on the page: http://python.org<

4条回答
  •  孤街浪徒
    2020-11-30 01:27

    text='Python' searches for elements that have the exact text you provided:

    import re
    from BeautifulSoup import BeautifulSoup
    
    html = """

    exact text

    almost exact text

    """ soup = BeautifulSoup(html) print soup(text='exact text') print soup(text=re.compile('exact text'))

    Output

    [u'exact text']
    [u'exact text', u'almost exact text']
    

    "To see if the string 'Python' is located on the page http://python.org":

    import urllib2
    html = urllib2.urlopen('http://python.org').read()
    print 'Python' in html # -> True
    

    If you need to find a position of substring within a string you could do html.find('Python').

提交回复
热议问题