Python 在HTML文件中查找字符串?

Python 在HTML文件中查找字符串?,python,html,Python,Html,这里没有。我试图用Python打印HTML文件中包含子字符串的行。我知道字符串在文件中,因为当我在html文件中按住ctrl+f键搜索字符串时,我找到了它。但是,当我运行代码时,它不会打印期望的结果。有人能解释一下我做错了什么吗 import requests import datetime from BeautifulSoup import BeautifulSoup now =datetime.datetime.now() cmonth = now.month cday = now.

这里没有。我试图用Python打印HTML文件中包含子字符串的行。我知道字符串在文件中,因为当我在html文件中按住ctrl+f键搜索字符串时,我找到了它。但是,当我运行代码时,它不会打印期望的结果。有人能解释一下我做错了什么吗

import requests
import datetime


from BeautifulSoup import BeautifulSoup

now =datetime.datetime.now()

cmonth = now.month
cday = now.day
cyear = now.year
find = 'boxscores/201'


url = 'http://www.basketball-reference.com/boxscores/index.cgi?lid=header_dateoutput&month={0}&day=17&year={2}'.format(cmonth,cday,cyear)
response = requests.get(url)
html = response.content
print html

for line in html:
    if find in line:
        print line

在requests包response.content中是一个字符串,因此您应该按如下方式搜索:

if find in html:
    # do something
通过使用

用于html中的行


您正在迭代字符串中的单个字符,而不是行。

正如snakecharmerb所说,通过使用

for line in html :
当html是字符串而不是行时,可以对其字符进行迭代。但是你可以用

for line in html.split("\n") :

对这两行进行迭代。

将两个答案相加。response.content以字节为单位。必须使用response.text才能使用string和do.split(“\n”)