簡體   English   中英

Python Web Scraping - 導航到Next_Page鏈接並獲取數據

[英]Python Web Scraping - Navigating to Next_Page link and obtaining data

我正在使用Python和Beautiful Soup從Civic Commons獲取可用軟件的網址- 社交媒體鏈接。 我想要所有社交媒體軟件的鏈接(分布在20頁)。 我能夠獲得第一頁中列出的軟件的URL。

下面是我為獲取這些值而編寫的Python代碼。

from bs4 import BeautifulSoup
import re
import urllib2

base_url = "http://civiccommons.org"
url = "http://civiccommons.org/software-functions/social-media"
page = urllib2.urlopen(url)
soup = BeautifulSoup(page.read())

list_of_links = [] 
for link_tag in soup.findAll('a', href=re.compile('^/apps/.*')):
   string_temp_link = base_url+link_tag.get('href')
   list_of_links.append(string_temp_link)

list_of_links = list(set(list_of_links))  

for link_item in list_of_links:
   print link_item

print ("\n")

#Newly added code to get all Next Page links from a url    
next_page_links = [] 
for link_tag in soup.findAll('a', href=re.compile('^/.*page=')):
   string_temp_link = base_url+link_tag.get('href')
   next_page_links.append(string_temp_link)
for next_page in next_page_links:
   print next_page

我用/ apps / regex來獲取軟件列表。

但我想知道是否有更好的方法來瀏覽下一頁。 我可以使用正則表達式“* page =”匹配下一頁鏈接。 但這會給出重復的頁面列表。

我怎樣才能以更好的方式做到這一點?

看頁面,有5頁,最后一頁是“......?page = 4”,所以,我們知道有第一頁,然后是page = 1到page = 4 ...

<li class="pager-last last">
<a href="/software-licenses/gpl?page=4" title="Go to last page">last »</a>
</li>

所以你可以通過類(或標題)檢索它,然后解析href ...

from urlparse import urlparse, parse_qs
for pageno in xrange(1, int(parse_qs(urlparse(url).query)['page'][0]) + 1):
    pass # do something useful here like building a url string with pageno

暫無
暫無

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

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