2017-05-24 86 views
1

剛剛在編程前一週左右,正在使用BeautifulSoup和https://cagematch.net開發一個刮板來獲取Python摔跤元數據。Python - 更改BeautifulSoup URL的顯示內容?

這裏是我的代碼:

from BeautifulSoup import BeautifulSoup 
import urllib2 

link = "https://www.cagematch.net/?id=8&nr=12&page=4" 
print link 
url = urllib2.urlopen(link) #Cagematch URL for PWG Events 
content = url.read() 
soup = BeautifulSoup(content) 

events = soup.findAll("tr", { "class" : "TRow" }) #Captures all event classes into a list, each event on site is separated by '<tr class="TRow">' 

for i in events[1:12]: #For each event, only searches over a years scope 
    data = i.findAll("td", { "class" : "TCol TColSeparator"}) #Captures each class on an event into a list item, separated by "<td class="TCol TColSeparator>" 
    date = data[0].text #Grabs Date of show, date of show is always first value of "data" list 
    show = data[1].text #Grabs name of show, name of show is always second value of "data" list 
    status = data[2].text #Grabs event type, if "Event (Card)" show hasn't occurred, if "Event" show has occurred. 

    print date, show, status 

    if status == "Event": #If event has occurred, get card data 
    print "Event already taken place" 
    link = 'https://cagematch.net/' + data[4].find("a", href=True)['href'] 
    print content 

這樣的想法是:從原始鏈接

  1. 搜索所有的事件列表,獲得它已經發生秀,秀的名字和狀態的日期。
  2. 如果發生事件,進入卡片頁面並獲取卡片內容(尚未完成,現在的功能只是打印該卡片頁面)。

1完美的作品,它去的網站很好,並得到它所需要的。 2沒有。

我在if語句中重新聲明我的「鏈接」變量。鏈接變量更改爲正確的鏈接。但是,當試圖再次打印內容時,它仍會從最初聲明鏈接的時候進入原始頁面。

如果我重新聲明瞭它的所有變量,但肯定還有另一種方法可以做到這一點?

回答

2

你就不會觸發頁面內容被重新定義link變量只是改變 - 你必須請求和新的鏈接下載頁面:

link = 'https://cagematch.net/' + data[4].find("a", href=True)['href'] 
url = urllib2.urlopen(link) 
content = url.read() 

其他一些注意事項:

  • 您使用的是非常過時BeautifulSoup版本3.更新到BeautifulSoup 4

    pip install beautifulsoup4 --upgrade 
    

    ,改變你的進口:

    from bs4 import BeautifulSoup 
    
  • 您可以通過切換到requests和重用多個請求同一個域相同的會話提高性能

  • 建議使用urljoin()來連接URL的部分

+0

感謝您的迴應,我很感激。 – ASolidBPlus

+0

我已根據您的反饋對代碼進行了更改,但是想知道是否有縮短它的時間,所以我不必每次都想要更改url時編寫所有這些代碼行?這是我可以使用的功能嗎? – ASolidBPlus

+0

你可以用'link'作爲參數輕鬆地將你的代碼包裝在一個函數中 –