[英]How to make search each page with given two inputs of page in python 3
我創建了一個程序來僅搜索如下所示的一頁。
import requests
from bs4 import BeautifulSoup
page1 = input("Enter Page Number: ")
jd = input("Enter File text name: ")
with open('E:/demo/' + jd + '.txt', 'a') as f:
f.write(page1 + '\n')
url = 'http://localhost:8888/'
url_ok = url + page1
r = requests.get(url_ok)
soup = BeautifulSoup(r.content)
for link in soup.find_all("a"):
if link.text[0:2] == 'GT':
print(link.text)
f.write(link.text + '\n')
我在http:// localhost:8888 /上有一台服務器,它有許多頁面,其編號如: -http:// localhost:8888/1 http:// localhost:8888/2 http:// localhost:8888/3 http:// localhost:8888/4 http:// localhost:8888/5 .. ... http:// localhost:8888/1000000
等等。 該程序僅占用一頁,並搜索結果並將其寫入文件。 我想創建一個循環,以便可以將兩個頁碼用作第5頁和第10頁的輸入。 因此,將根據該程序從第5頁,第6頁,第7頁,第8頁,第9頁和第10頁中搜索所有內容。
您可以創建一個像這樣的循環:
import requests
from bs4 import BeautifulSoup
start, end = 5, 10
base_url = "http://localhost:8888/"
for page in range(start, end):
with open("E:/demo/file{}.txt".format(page), 'a') as f:
url = base_url + str(page)
r = requests.get(url)
soup = BeautifulSoup(r.content)
for link in soup.find_all("a"):
if link.text[0:2] == 'GT':
print(link.text)
f.write(link.text + '\n')
請注意,您仍然可以更改開始和結束頁碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.