2016-03-19 54 views
1

Python noob here。我試圖用Python在HTML文件中打印包含子字符串的行。我知道該字符串在文件中,因爲當我按Ctrl + f在html文件中搜索的字符串時,我發現它。但是,當我運行我的代碼時,它不打印所需的結果。有人能解釋我做錯了什麼嗎?尋找HTML文件中的字符串?

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 

回答

2

在請求包response.content是一個字符串,所以你應該這樣搜索:

if find in html: 
    # do something 

通過遍歷response.content與

for line in html

你遍歷字符串中的單個字符,而不是行。

1

正如snakecharmerb說,通過使用

for line in html : 

您遍歷HTML的字符當它是一個字符串,而不是行。但是你可以使用

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

遍歷行。