2015-11-09 128 views
-2

我刮從https://www.open2study.com/courses 我得到的所有圖像源,但不知道如何顯示圖像(而不是鏈接)在一個html文件上的2列(標題和圖像的一列)表。高手幫我解決了嗎?如何從網站上抓取圖片並將其顯示在html文件中?

import urllib 
from bs4 import BeautifulSoup 

titles = [] 
images = [] 

r = urllib.urlopen('https://www.open2study.com/courses').read() 
soup = BeautifulSoup(r) 

for i in soup.find_all('div', {'class': "courses_adblock_rollover"}): 
    titles.append(i.h2.text) 

for i in soup.find_all(
    'img', { 
     'class': "image-style-course-logo-subjects-block"}): 
    images.append(i.get('src')) 

with open('test.txt', "w") as f: 
    for i in zip(titles, images): 
     f.write(i[0].encode('ascii', 'ignore') + 
       '\n'+i[1].encode('ascii', 'ignore') + 
       '\n\n') 

header = '<!doctyle html><html><head><title>My Title</title></head><body>' 
body = '<table><thead><tr><th></th><th></th></tr>' 

footer = '</table></body></html>' 
img_tag = '<img src=,{}">' 


with open('test.txt', 'r') as input, open('test.html', 'w') as output: 
    output.write(header) 
    output.write(body) 

    for line in input: 
     col1 = line.rstrip().split() 
     col2 = line.rstrip().split() 
     output.write('<tr><td>{}</td><td>{}</td></tr>\n'.format(col1, col2)) 

    output.write(footer) 
+1

請澄清之情況'顯示images' – SIslam

+0

請你寫已經 –

+0

你的迭代器是錯誤的代碼更新您的問題.. .it每次迭代一行,而您正在考慮它兩行,即col1和col2 –

回答

1

這是很簡單的problem.try這個

for line in input: 
    #ignore blank lines 
    if line == '\n': 
     continue 
    #why were you spliting here? 
    col1 = line.rstrip() 
    #read next line 
    col2 = next(input).rstrip() 
    output.write('<tr><td>{}</td><td><img src="{}" style="width: 160px; height: 100px"></td></tr>\n'.format(col1, col2)) 
+0

@ Saad Abdullah但我該如何顯示圖像S'您的代碼只顯示圖片源鏈接 – Mina

+0

使用該圖片標籤。 –

+0

答案更新!嘗試下次Google搜索... –

相關問題