2017-01-05 6 views
2

意図:反復リンク取り除いた文字列

1.Accessセレンとhttp://blogdobg.com.br/のメインページ。

2.Identify記事は、BS4に

3.Insert各リンクをリンクし、テキストに引っ張る

問題:私はすべてのリンクを印刷したり、BS4 に単一のリンクを移動する限り取得することができます 解析と印刷のために。同じリンクで終わった各リンクの読み込みは、何度も繰り返されました。

私はちょうど2日前に自分自身を勉強し始めました。だから、どんな指針にも感謝します。

from selenium import webdriver 
from lxml import html 
import requests 
import re 
from bs4 import BeautifulSoup 

def read (html): 
    html = browser.page_source 
    soup = BeautifulSoup(html,"html.parser") 
    for string in soup.article.stripped_strings: 
      print(repr(string)) 

path_to_chromedriver = '/Users/yakir/chromedriver' 
browser = webdriver.Chrome(executable_path = path_to_chromedriver) 

url = 'http://blogdobg.com.br/' 
browser.get(url) 

articles = browser.find_elements_by_xpath("""//*[contains(concat(" ", @class, " "), concat(" ", "entry-title", " "))]//a""") 

#get all the links 
for link in articles: 
    link.get_attribute("href") 

#Attempt to print striped string from each link's landing page 
for link in articles: 
     read(link.get_attribute("href")) 

##method for getting one link to work all the way through (currently commented out) 
#article1 = articles[1].get_attribute("href") 
#browser.get(article1) 
#read(article1) 

答えて

0

すべての関数の最初に、この関数内で直接html変数を定義しながら、read()htmlパラメータがあります。これは意味をなさない:あなたの引数はとにかく無視され、BeautifulSoup(html,"html.parser")html = browser.page_sourceから値を取得しますが、ないもう一つの問題html

引数から:あなたは

for link in articles: 
    link.get_attribute("href") 

であなたをすべてのリンクを取得することはできません必要がありますlistを使用し、各反復に値を追加:

link_list = [] 
for link in articles: 
    link_list.append(link.get_attribute("href")) 

その後、あなたはあなたのようなリンクを使用することができます。

for link in link_list: 
    r = requests.get(link) 
    ... 
    # do whatever you want to do with response 
関連する問題