Python字符串替换不适合我

时间:2016-07-17 23:27:55

标签: python django function

我试图在python中使用字符串替换,但它无法正常工作。我试图用空格替换字符。继承我的代码。

def panties():
        pan_url = 'http://www.panvideos.com'
        html = requests.get(pan_url, headers=headers)
        soup = BeautifulSoup(html.text, 'html5lib')
        video_row = soup.find_all('div', {'class': 'video'})

        def youtube_link(url):
            youtube_page = requests.get(url, headers=headers)
            soupdata = BeautifulSoup(youtube_page.text, 'html5lib')
            video_row = soupdata.find('div', {'class': 'video-player'})
            entries = [{'text': str(div),
                        } for div in video_row][3]['text']

            removed = '<script type="text/javascript">jwplayer("video-setup").setup('
            newstring = entries.replace(removed, "")


            return newstring

        entries = [{'text': div.h4.text,
                    'href': div.a.get('href'),
                    'tube': youtube_link(div.a.get('href')),
                    } for div in video_row][:1]

        return entries

但它仍然会返回

<script type="text/javascript">jwplayer("video-setup").setup({file:"http://www.youtube.com/watch?v=jucBuAzuZ0E",image:"http://i1.ytimg.com/vi/jucBuAzuZ0E/maxresdefault.jpg",primary:"html5",stretching:"fill","controlbar":"bottom",width:"100%",aspectratio:"16:9",autostart:"true",logo:{file:"http://www.panvideos.com/uploads/bien-png578aab16676e1.png",position:"bottom-right",link:"http://www.panvideos.com/"},sharing:{link:"http://www.panvideos.com/video/3020/alejandro-sanz-deja-que-te-bese-ft-marc-anthony-official-video-/","sites":["facebook","twitter","linkedin","pinterest","tumblr","googleplus","reddit"]}});</script>

而不是

{file:"http://www.youtube.com/watch?v=jucBuAzuZ0E",image:"http://i1.ytimg.com/vi/jucBuAzuZ0E/maxresdefault.jpg",primary:"html5",stretching:"fill","controlbar":"bottom",width:"100%",aspectratio:"16:9",autostart:"true",logo:{file:"http://www.panvideos.com/uploads/bien-png578aab16676e1.png",position:"bottom-right",link:"http://www.panvideos.com/"},sharing:{link:"http://www.panvideos.com/video/3020/alejandro-sanz-deja-que-te-bese-ft-marc-anthony-official-video-/","sites":["facebook","twitter","linkedin","pinterest","tumblr","googleplus","reddit"]}});</script>    

我做错了什么?

1 个答案:

答案 0 :(得分:1)

我想通了我必须将条目转换为类似的字符串

oldstring = str(entries)
removed = '<script type="text/javascript">jwplayer("video-setup").setup('
newstring = oldstring.replace(removed, "")

return newstring

它有效。我想返回的不是字符串。