【发布时间】:2016-11-19 15:07:26
【问题描述】:
我正在开发一个使用 beatifulsoup、Python、requests 和 django 的应用程序。我一直在掌握如何使用美丽的汤。但是,向下钻取似乎有时会混淆不同的元素。我创建了一个功能,虽然不是最好的,它从帖子中抓取链接并使用这些链接转到帖子详细信息页面。并从该页面抓取包含 Facebook 网址和与之关联的图像的脚本数据。这是代码
来自我的 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
从我的观点.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
分别是视频和图像。我怎样才能做到这一点。我的代码不是一成不变的,我不介意更改它以使其工作。感谢我提前提出的任何建议。
【问题讨论】:
标签: python json django beautifulsoup