使用Python BeautifulSouplxml刮取所有链接

问题描述 投票:1回答:6

http:/www.snapdeal.com

我试图从这个网站上刮取所有链接,当我这样做时,我得到了一个意想不到的结果。我发现这是因为javascript的缘故。

在 "查看所有类别 "标签下,你会发现所有主要的产品类别。如果你把鼠标悬停在任何类别上,它将展开类别。我希望这些链接从每个主要类别。

url = 'http://www.snapdeal.com/'
data = urllib2.urlopen(url)
page = BeautifulSoup(data)
#print data
for link in page.findAll('a'):
       l = link.get('href')
       print l

但是,这给我的结果和我预期的不一样(我关闭了javascript,看了一下页面源,输出的是这个源)。

我只是想从每个大类中找到所有的子链接。任何建议都将被感激。

python python-2.7 web-scraping beautifulsoup lxml
6个回答
2
投票

发生这种情况只是因为你让BeautifulSoup选择了自己的最佳解析器,而且你可能没有安装lxml。

最好的选择是使用 html.parser 来解析网址。

from bs4 import BeautifulSoup
import urllib2
url = 'http://www.snapdeal.com/'
data = urllib2.urlopen(url).read()

page = BeautifulSoup(data,'html.parser')

for link in page.findAll('a'):
       l = link.get('href')
       print l  

这对我来说是有效的。确保安装依赖。


1
投票

分类菜单 是你要找的网址。许多网站使用 XHR(XMLHTTPRequest). 为了检查网站的组件,请熟悉Firefox中的Firebug附加组件或Chrome中的开发者工具(内置附加组件)。你可以在上述附加组件的网络标签下检查网站使用的XHR。


0
投票

我觉得你应该试试其他库,比如 它为你提供了一个web驱动,这就是这个库的优势,对于我自己来说,我无法用bs4处理javascript。


0
投票

使用网页抓取工具,如 scrapymechanize在机械化,以获得所有链接在snapdeal主页。

br=Browser()
br.open("http://www.snapdeal.com")
for link in browser.links():
    print link.name
    print link.url

0
投票

我一直在寻找一种方法来从只在实际浏览器中呈现的网页中刮取链接,但希望结果能在无头浏览器中运行。

我可以使用 幻象JS硒和 靓汤

#!/usr/bin/python

import bs4
import requests
from selenium import webdriver

driver = webdriver.PhantomJS('phantomjs')
url = 'http://www.snapdeal.com/'
browser = driver.get(url)
content = driver.page_source
soup = bs4.BeautifulSoup(content)
links = [a.attrs.get('href') for a in soup.find_all('a')]
for paths in links:
    print paths
driver.close()

0
投票

下面的例子将适用于这两种情况 HTTPHTTPS. 我写这个答案是为了告诉大家,如何在这两种情况下使用 Python 2Python 3.

Python 2

这是受以下启发 本回答.

from bs4 import BeautifulSoup
import urllib2
url = 'https://stackoverflow.com'
data = urllib2.urlopen(url).read()

page = BeautifulSoup(data,'html.parser')

for link in page.findAll('a'):
       l = link.get('href')
       print l 

Python 3

from bs4 import BeautifulSoup
from urllib.request import urlopen
import ssl

# to open up HTTPS URLs
gcontext = ssl.SSLContext()

# You can give any URL here. I have given the Stack Overflow homepage
url = 'https://stackoverflow.com'
data = urlopen(url, context=gcontext).read()

page = BeautifulSoup(data, 'html.parser')

for link in page.findAll('a'):
    l = link.get('href')
    print(l)

其他语言

关于其他语言,请参见 本回答.

© www.soinside.com 2019 - 2024. All rights reserved.