Python Webscraping

时间:2016-12-02 14:16:10

标签: python web-scraping beautifulsoup

我试图使用Python从网站上抓取数据。当我在浏览器中查看源代码时,我可以看到我正在寻找的所有内容。但是,当我使用BeautifulSoup下载代码时,我只获得了我想要的部分数据。

我知道BeautifulSoup不能使用javascript,(我根本不懂javascript)而且我想知道是否有下载所有原始源代码的方法(基本上很难得到)复制)即使网站的某些部分是用javascript完成的。​​

到目前为止,这是我的代码:

 r = requests.get('https://www.example.com/example/example')
 data = BeautifulSoup(r.content)
 example1 = data.find_all("class_="example2") 
 examples = []
 for example in example1:
     examples.append(link.get('href'))

我知道如果没有实际的源代码,很难彻底回答我的问题。不幸的是我无法显示代码!希望它不是一个太大的问题。

3 个答案:

答案 0 :(得分:1)

很难在没有浏览器的情况下获得动态(基于JavaScript)网站的完整副本,这就是为什么获取此类副本的最简单方法是使用浏览器。

您可以查看PhantomJSSelenium来控制浏览器并下载HTML,或者只使用subprocess运行PhantomJS。

下载网站内容的非常简单的PhantomJS脚本:

"use strict";
var fs = require('fs');
var system = require('system');
var webpage = require('webpage');
if (system.args.length != 2) {
    console.log('Usage: gethtml.js <url>');
    phantom.exit(1);
} else {
    var url = system.args[1];
    var page = webpage.create();
    page.open(url, function(status) {
        if (status !== 'success') {
            phantom.exit(2);
        }
        setTimeout(function() {
            console.log(page.content);
            phantom.exit();
        }, 500);
    });
}

这等待500毫秒之前&#34;下载&#34;,这取决于站点和互联网连接这是不够的或太多,您可以通过等待PhantomJS使用{{1停止下载数据X秒来改进它回调。

答案 1 :(得分:1)

也许不是最好的解决方案,但如果您只想解析链接,这里是我的2美分。

import requests
from BeautifulSoup import BeautifulSoup
r = requests.get('http://www.examples.com')
data = BeautifulSoup(r.content)
examples = []
for d in data.findAll('a'):
    examples.append(d)

当然你可以搜索类:

my_as = soup.findAll("a", { "class" : "someclass" })

答案 2 :(得分:0)

你的代码错了,毫无意义:

r = requests.get('https://www.example.com/example/example')
data = BeautifulSoup(r.content)
aes = data.find_all("class_="example2") 
result = []
for a in aes:
    result.append(a.attrs['href'])