2017-05-11 9 views
2

クローラを実行すると、リストとして結果が取得されます。しかし、私はそれを通常の文字列で2列に表示することを期待していました。ご意見ありがとうございます。このようなスクラップしたデータをリストから通常の文字列に変換できません

import requests 
from lxml import html 

url="http://www.wiseowl.co.uk/videos/" 
def Startpoint(links): 
    response = requests.get(links) 
    tree = html.fromstring(response.text) 
    Title= tree.xpath("//p[@class='woVideoListDefaultSeriesTitle']/a/text()") 
    Link=tree.xpath("//p[@class='woVideoListDefaultSeriesTitle']/a/@href") 
    print(Title,Link) 

Startpoint(url) 

持つ結果: enter image description here

はしかし、私が期待されるような出力: enter image description here

答えて

1

はこのように、両方のリストの順番を反復処理してみてください。

import requests 
from lxml import html 

url="http://www.wiseowl.co.uk/videos/" 
def Startpoint(links): 
    response = requests.get(links) 
    tree = html.fromstring(response.text) 
    Title= tree.xpath("//p[@class='woVideoListDefaultSeriesTitle']/a/text()") 
    Link=tree.xpath("//p[@class='woVideoListDefaultSeriesTitle']/a/@href") 
    for i,j in zip(Title, Link): 
     print('{:<70}{}'.format(i,j)) 

Startpoint(url) 
+0

ワウ!これは私が期待していたものです。そのような素晴らしい解決策をお寄せいただきありがとうございました。トリプル "t"の使い方は私にはあいまいです。私の無知を許しなさい。あなたはしばらく答えてくれるでしょう。 – SIM

+0

ああ、実際には出力にスペースがあったので、私はそれをつけてくれた:P何か文字列の操作をしようとしていたが、失敗した。しかし出力は正しいです – Shashank

2

をごTitleLinkには実際には1つの要素が含まれていませんいずれも両方とものすべてのタイトルとリンク(これらのXPath式は複数の要素に一致します)のをリストしています。

のでtitle, linkペアのリストを取得するためには、あなたがそれらを一緒にzip()する必要があります。

pairs = zip(titles, links) 

あなたがforループを使用して、それらのペアを反復処理し、そして左のアイテムを印刷することができ、ということだたら、

print('{:<70}{}'.format(title, link)) 

(左整列のアイテムを印刷する方法の詳細については、this answerを参照してください):あなたが列を取得して正当化。


一緒にすべて:

import requests 
from lxml import html 

url = "http://www.wiseowl.co.uk/videos/" 


def startpoint(links): 
    response = requests.get(links) 
    tree = html.fromstring(response.text) 
    titles = tree.xpath("//p[@class='woVideoListDefaultSeriesTitle']/a/text()") 
    links = tree.xpath("//p[@class='woVideoListDefaultSeriesTitle']/a/@href") 
    pairs = zip(titles, links) 

    for title, link in pairs: 
     # Replace '70' with whatever you expect the maximum title length to be 
     print('{:<70}{}'.format(title, link)) 

startpoint(url) 
+0

おかげでルーカス・グラフさん、あなたの答えも問題を解決します。 – SIM

1

あなたはタイトルとURLを各リンクをループして印刷することができます。

import requests 
from lxml import html 

url="http://www.wiseowl.co.uk/videos/" 
def Startpoint(links): 
    response = requests.get(links) 
    tree = html.fromstring(response.text) 
    links = tree.xpath("//p[@class='woVideoListDefaultSeriesTitle']/a") 
    for link in links: 
     print('{title:<70}{url}'.format(title=link.text, url=link.attrib.['href'])) 

Startpoint(url) 
+0

ハケン・リッドさん、ありがとうございました。また、問題を解決します。 – SIM

関連する問題