簡體   English   中英

網絡抓取工具 - 以下鏈接

[英]Web crawler - following links

請多多包涵。 我是Python的新手 - 但有很多樂趣。 我正在嘗試編寫一個網絡爬蟲代碼,用於搜索丹麥最后一次公投的選舉結果。 我設法從主頁面中提取所有相關鏈接。 現在我希望Python遵循92個鏈接中的每一個,並從每個頁面中收集9條信息。 但我很困惑。 希望你能給我一個提示。

這是我的代碼:

import requests
import urllib2 
from bs4 import BeautifulSoup

# This is the original url http://www.kmdvalg.dk/

soup = BeautifulSoup(urllib2.urlopen('http://www.kmdvalg.dk/').read())

my_list = []
all_links = soup.find_all("a")

for link in all_links:
    link2 = link["href"]
    my_list.append(link2)

for i in my_list[1:93]:
    print i

# The output shows all the links that I would like to follow and gather information from. How do I do that?

這是我使用lxml解決方案。 它與BeautifulSoup類似

import lxml
from lxml import html
import requests

page = requests.get('http://www.kmdvalg.dk/main')
tree = html.fromstring(page.content)
my_list = tree.xpath('//div[@class="LetterGroup"]//a/@href') # grab all link
print 'Length of all links = ', len(my_list)

my_list是一個包含所有鏈接的列表。 現在,您可以使用for循環來抓取每個頁面內的信息。

我們可以遍歷每個鏈接。 在每個頁面中,您可以提取信息作為示例。 這僅適用於頂級表格。

table_information = []
for t in my_list:
    page_detail = requests.get(t)
    tree = html.fromstring(page_detail.content)
    table_key = tree.xpath('//td[@class="statusHeader"]/text()')
    table_value = tree.xpath('//td[@class="statusText"]/text()') + tree.xpath('//td[@class="statusText"]/a/text()')
    table_information.append(zip([t]*len(table_key), table_key, table_value))

對於頁面下方的表格,

table_information_below = []
for t in my_list:
    page_detail = requests.get(t)
    tree = html.fromstring(page_detail.content)
    l1 = tree.xpath('//tr[@class="tableRowPrimary"]/td[@class="StemmerNu"]/text()')
    l2 = tree.xpath('//tr[@class="tableRowSecondary"]/td[@class="StemmerNu"]/text()')
    table_information_below.append([t]+l1+l2)

希望這有幫助!

一個簡單的方法是遍歷您的URL列表並分別解析它們:

for url in my_list:
    soup = BeautifulSoup(urllib2.urlopen(url).read())
    # then parse each page individually here

或者,您可以使用Futures顯着加快速度。

from requests_futures.sessions import FuturesSession

def my_parse_function(html):
    """Use this function to parse each page"""
    soup = BeautifulSoup(html)
    all_paragraphs = soup.find_all('p')
    return all_paragraphs

session = FuturesSession(max_workers=5)
futures = [session.get(url) for url in my_list]

page_results = [my_parse_function(future.result()) for future in results]

這將是我解決您問題的方法

 import requests
from bs4 import BeautifulSoup


def spider():
    url = "http://www.kmdvalg.dk/main"
    source_code = requests.get(url)
    plain_text = source_code.text
    soup = BeautifulSoup(plain_text, 'html.parser')

    for link in soup.findAll('div', {'class': 'LetterGroup'}):
        anc = link.find('a')
        href = anc.get('href')

        print(anc.getText())
        print(href)
        # spider2(href) call a second function from here that is similar to this one(making url = to herf)
        spider2(href)
        print("\n")


def spider2(linktofollow):
    url = linktofollow
    source_code = requests.get(url)
    plain_text = source_code.text
    soup = BeautifulSoup(plain_text, 'html.parser')

    for link in soup.findAll('tr', {'class': 'tableRowPrimary'}):
        anc = link.find('td')

        print(anc.getText())
    print("\n")


spider()

它沒有完成...我只從表中得到一個簡單的元素,但你明白了它應該如何工作。

這是我的最終代碼順利運行。 如果我能做得更聰明,請告訴我!

import urllib2 
from bs4 import BeautifulSoup
import codecs

f = codecs.open("eu2015valg.txt", "w", encoding="iso-8859-1")

soup = BeautifulSoup(urllib2.urlopen('http://www.kmdvalg.dk/').read())

liste = []

alle_links = soup.find_all("a")

for link in alle_links:
    link2 = link["href"]
    liste.append(link2)

for url in liste[1:93]:
    soup = BeautifulSoup(urllib2.urlopen(url).read().decode('iso-8859-1'))
    tds = soup.findAll('td')
    stemmernu = soup.findAll('td', class_='StemmerNu')
    print >> f, tds[5].string,";",tds[12].string,";",tds[14].string,";",tds[16].string,";", stemmernu[0].string,";",stemmernu[1].string,";",stemmernu[2].string,";",stemmernu[3].string,";",stemmernu[6].string,";",stemmernu[8].string,";",'\r\n'

f.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM