[英]retrieve specific links from web page using python and BeautifulSoup
[英]retrieve links from web page using python and BeautifulSoup than select 3 link and run it 4 times
這是代碼。
import urllib
from BeautifulSoup import *
url = raw_input('Enter - ')
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
# Retrieve all of the anchor tags
tags = soup('a')
for tag in tags:
print tag.get('href', None)
有18個鏈接。 現在需要獲取位置 3 意味着來自輸出的第三個鏈接並將該鏈接作為輸入提供給 html 並再次運行它並執行 4 次。 以及在位置 3 處的最后輸出比打印出名稱。
[ https://pr4e.dr-chuck.com/tsugi/mod/python-data/data/known_by_Fikret.html][1]
這將從上述 HTML 返回 18 個鏈接。 現在我們需要選擇第 3 個鏈接,並提供第 3 個鏈接作為 'url' 的輸入,並按照上述循環進行 4 次,最后一個鏈接出現的內容比獲得第一個鏈接中的名稱 'fikret' 是名稱以及最后一個鏈接中的內容是我們的輸出。 希望這可以幫助。 謝謝你的調查。
我能夠通過以下方式完成您的作業(請花點時間學習):
import urllib
from bs4 import BeautifulSoup
# This function will get the Nth link object from the given url.
# To be safe you should make sure the nth link exists (I did not)
def getNthLink(url, n):
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html, 'html.parser')
tags = soup('a')
return tags[n-1]
url = "https://pr4e.dr-chuck.com/tsugi/mod/python-data/data/known_by_Fikret.html"
# This iterates 4 times, each time grabbing the 3rd link object
# For convenience it prints the url each time.
for i in xrange(4):
tag = getNthLink(url,3)
url = tag.get('href')
print url
# Finally after 4 times we grab the content from the last tag
print tag.contents[0]
做到這一點的簡單方法是:
url = input('Enter url -')
count = int(input('Enter count -'))
position = int(input('Enter position-'))
for i in range(count):
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html, 'html.parser')
tags = soup('a')
tag = tags[position - 1] #get the URL link from an array
url = tag.get('href',None)
print('Retrieving: ' + URL)
print(tag.contents[0])
我使用的是 Python 3.5,所以這里是調整后的版本(和 w/o def 函數):
import urllib
import bs4
import re
times = 7 #number of times to click url
line_numb = 18 #I'm converting to python count later
url = "http://python-data.dr-chuck.net/known_by_Terri.html "
for _ in range(times):
html = urllib.request.urlopen(url).read()
soup = bs4.BeautifulSoup(html, "lxml")
tags = soup.find_all('a')
url=tags[line_numb-1].get('href')
print (url)
name = re.findall('known_by_(.*).html',url)
print (name)
from urllib.request import urlopen
import BeautifulSoup
import ssl
ctx = ssl.create_default_context() # To ignore SSL certificate Error
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
url = input('Enter - ')
count=int(input('Enter count: '))
pos=int(input('Enter position: '))
i=1
while True:
if i>count: # to run the loop at specified no of times.
break
i=i+1
html=urlopen(url, context=ctx).read() #to open the url
soup=BeautifulSoup(html,"html.parser")
tags=soup('a') #extracts list of anchor attributes
url=tags[pos-1].get('href',None) #extract tag at specified position . Indexing of attributes start with zero therefore pos-1
print (url)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.