[英]Extract the last n characters of a string in a list
我有一個鏈接列表,其中有些有頁碼,有些沒有。 我正在嘗試抓取網站以獲取頁碼,但它采用以下格式:'\n\n\n\n\n\n\n\n«\nPrevious\n\n\n\n\n \n\n1\n\n2\n\n3\n\n\x85\n\n23'
有人可以幫我提取列表的最后 2 個字符嗎?
這是我正在使用的代碼和我得到的 output。
for i in range(0, len(links)):
url = links[i]
response = requests.get(url, cookies)
soup = BeautifulSoup(response.content)
pr = [f.text for f in soup.find_all(class_='lia-paging-full-wrapper lia-paging-pager lia-paging-full-left-position lia-discussion-page-message-pager lia-forum-topic-page-gte-5-pager lia-component-message-pager')]
ed = [i.split('\n\n\n\n\n\nNext\n»\n\n\n\n', 1)[0] for i in pr]
print(ed)
我得到的 output 是這樣的:
['\n\n\n\n\n\n\n\n«\nPrevious\n\n\n\n\n\n\n1\n\n2\n\n3\n\n\x85\n\n23']
[]
['\n\n\n\n\n\n\n\n«\nPrevious\n\n\n\n\n\n\n1\n\n2\n\n3']
['\n\n\n\n\n\n\n\n«\nPrevious\n\n\n\n\n\n\n1\n\n2\n\n3']
[]
[]
[]
[]
['\n\n\n\n\n\n\n\n«\nPrevious\n\n\n\n\n\n\n1\n\n2']
['\n\n\n\n\n\n\n\n«\nPrevious\n\n\n\n\n\n\n1\n\n2\n\n3\n\n\x85\n\n16']
[]
[]
[]
['\n\n\n\n\n\n\n\n«\nPrevious\n\n\n\n\n\n\n1\n\n2']
[]
我怎樣才能得到最后 2-3 個字符,因為它們代表頁碼?
你可以做ed[-2:]
但我注意到你有 1 到 2 位數字,有很多方法,一種方法是使用正則表達式查找字符串最后的數字:
import re
pattern = re.compile('\d+$')
for i in range(0, len(links)):
url = links[i]
response = requests.get(url, cookies)
soup = BeautifulSoup(response.content)
pr = [f.text for f in soup.find_all(class_='lia-paging-full-wrapper lia-paging-pager lia-paging-full-left-position lia-discussion-page-message-pager lia-forum-topic-page-gte-5-pager lia-component-message-pager')]
ed = [i.split('\n\n\n\n\n\nNext\n»\n\n\n\n', 1)[0] for i in pr]
print(ed)
if ed:
page_count = pattern.findall(ed[0])
print(page_count[0])
else:
print('ed is empty!')
OUTPUT:
23
ed is empty!
3
3
ed is empty!
ed is empty!
ed is empty!
ed is empty!
2
16
ed is empty!
ed is empty!
ed is empty!
2
ed is empty!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.