2016-09-02 92 views
2

我试图从网站解析HTML内容,更改href和img src。 href更改成功,但img src不更改。Python BeautifulSoup替换img src

它的变量发生变化,但不是在HTML(POST_CONTENT):

<p><img alt="alt text" src="https://lifehacker.ru/wp-content/uploads/2016/08/15120903sa_d2__1471520915-630x523.jpg" title="Title"/></p> 

不_http://site.ru ...

<p><img alt="alt text" src="http://site.ru/wp-content/uploads/2016/08/15120903sa_d2__1471520915-630x523.jpg" title="Title"/></p> 

我的代码

if "app-store" not in url: 
     r = requests.get("https://lifehacker.ru/2016/08/23/kak-vybrat-trimmer/") 
     soup = BeautifulSoup(r.content) 

     post_content = soup.find("div", {"class", "post-content"}) 
     for tag in post_content(): 
      for attribute in ["class", "id", "style", "height", "width", "sizes"]: 
       del tag[attribute] 

     for a in post_content.find_all('a'): 
      a['href'] = a['href'].replace("https://lifehacker.ru", "http://site.ru") 

     for img in post_content.find_all('img'): 
      img_urls = img['src'] 
      if "https:" not in img_urls: 
       img_urls="http:{}".format(img_urls) 
      thumb_url = img_urls.split('/') 
      urllib.urlretrieve(img_urls, "/Users/kr/PycharmProjects/education_py/{}/{}".format(folder_name, thumb_url[-1])) 

      file_url = "/Users/kr/PycharmProjects/education_py/{}/{}".format(folder_name, thumb_url[-1]) 
      data = { 
       'name': '{}'.format(thumb_url[-1]), 
       'type': 'image/jpeg', 
      } 

      with open(file_url, 'rb') as img: 
       data['bits'] = xmlrpc_client.Binary(img.read()) 


      response = client.call(media.UploadFile(data)) 

      attachment_url = response['url'] 


      img_urls = img_urls.replace(img_urls, attachment_url) 



     [s.extract() for s in post_content('script')] 
     post_content_insert = bleach.clean(post_content) 
     post_content_insert = post_content_insert.replace('&lt;', '<') 
     post_content_insert = post_content_insert.replace('&gt;', '>') 

     print post_content_insert 

回答

1

看起来你从来没有把img_urls归还给img['src']。在块的最后尝试做到这一点。

img_urls = img_urls.replace(img_urls, attachment_url) 
img['src'] = img_urls 

...但首先,你需要改变你的with语句,它使用比其他img一些名称为您的文件对象。现在你已经掩盖了dom元素,你不能再访问它。

 with open(file_url, 'rb') as some_file: 
      data['bits'] = xmlrpc_client.Binary(some_file.read()) 
+0

已经尝试过,但 - IMG [“SRC”] = img_urls 类型错误:“文件”对象不支持项目分配 –

+0

哦,这是一个名称冲突的问题。编辑。 – Kevin

+0

工作 - 完美,非常感谢,并为noob问题抱歉。 –