如何从我的beautifulsoup结果返回的字典中提取值?

时间:2016-07-16 15:10:44

标签: python json django beautifulsoup

我正在开发一个使用beatifulsoup,Python,requests和django的应用程序。我一直在抓住如何使用美味的汤。但是向下挖掘似乎有些不同因素有时令人困惑。我创建了一个功能,尽管不是最好的,从帖子中删除链接并使用这些链接转到帖子详细信息页面。并从该页面中删除包含面部书籍URL的脚本数据以及与其关联的图像。这是代码

来自我的scraper.py

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]
        return entries

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

    return entries

来自我的views.py

   pan = panties()
    context = {
        'pan': pan,
    }
    return render(request, 'index.html', context)

并在我的模板中

{% for p in pan %}
   Title: {{p.text}}<br>
   Href: {{p.href}}<br>
   Tube: {{p.tube}}<hr>
{% endfor %}

并且继承了它的回报

Title: Juanka - Esperando por ti (Official Video)
Href: http://www.videos.com/video/2962/juanka-esperando-por-ti-official-video-/
Tube: {'text': '<script type="text/javascript">jwplayer("video-setup").setup({file:"http://www.youtube.com/watch?v=QL4JFUHd71o",image:"http://i1.ytimg.com/vi/QL4JFUHd71o/maxresdefault.jpg",primary:"html5",stretching:"fill","controlbar":"bottom",width:"100%",aspectratio:"16:9",autostart:"true",logo:{file:"http://www.panvideos.com/uploads/gopcds-png5787dbcd53a72.png",position:"bottom-right",link:"http://www.panvideos.com/"},sharing:{link:"http://www.panvideos.com/video/2962/juanka-esperando-por-ti-official-video-/","sites":["facebook","twitter","linkedin","pinterest","tumblr","googleplus","reddit"]}});</script>'}

我的事情是我只想要

http://www.youtube.com/watch?v=QL4JFUHd71o

http://i1.ytimg.com/vi/QL4JFUHd71o/maxresdefault.jpg

分别是视频和图像。我怎样才能做到这一点。我的代码并非一成不变,我不介意改变它以使其工作。感谢您提出任何建议。

1 个答案:

答案 0 :(得分:0)

如果我理解得很好,你想从你的p.tube BeautifulSoup对象中找到2个元素。我会称之为soup以便于理解。

首先,我会删除带有<script>函数的soup.text

然后我会使用正则表达式重新包https://docs.python.org/2/library/re.html找到.setup(来摆脱它之前的所有内容,并-2去掉); at结束

import re
s = re(".setup(", soup)
soup = soup[s.end:-2]

然后,为了将您的字符串转换为字典,我建议您使用ast.literal_evalConvert a String representation of a Dictionary to a dictionary?

不幸的是,(这很容易)你的字符串没有很好地格式化,很容易转换成字典。

因此,我会摆脱{},并与逗号分开,

soup = soup[1:-1]
l = soup.split(',')

希望,因为你要搜索的元素是前两个,你应该很容易找到它们