【发布时间】:2015-07-29 13:33:53
【问题描述】:
我正在使用漂亮的汤从页面中获取链接。 我想做的是随机选择一个链接并继续程序的其余部分。目前它正在使用所有链接并继续程序的其余部分,但我只希望它选择 1 个链接。
然后程序的其余部分将查看链接并确定它是否足以满足我的需求。如果它不够好,它将返回并单击另一个链接。并重复这些过程。
你知道如何让它做到这一点吗?
这是我当前用于查找链接的代码。
import requests
import os.path
from bs4 import BeautifulSoup
import urllib.request
import hashlib
import random
max_page = 1
img_limit = 5
def pic_spider(max_pages):
page = random.randrange(0, max_page)
pid = page * 40
pic_good = 1
while pic_good == 1:
if page <= max_pages:
url = 'http://safebooru.org/index.php?page=post&s=list&tags=yuri&pid=' + str(pid)
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, "html.parser")
id_list_location = os.path.join(id_save, "ids.txt")
first_link = soup.findAll('a', id=True, limit=img_limit)
for link in first_link:
href = "http://safebooru.org/" + link.get('href')
picture_id = link.get('id')
print("Page number = " + str(page + 1))
print("pid = " + str(pid))
print("Id = " + picture_id)
print(href)
if picture_id in open(id_list_location).read():
print("Already Downloaded or Picture checked to be too long")
else:
log_id(picture_id)
if ratio_get(href) >= 1.3:
print("Picture too long")
else:
#img_download_link(href, picture_id)
print("Ok download")
我不确定我会怎么做,所以任何想法都会帮助我,如果您有任何问题,请随时提问!
【问题讨论】:
-
如果
first_link是一个列表,你不能只做first_link[random_number],其中random_number在0和列表长度之间生成吗?我想findAll()返回所有元素的列表(似乎 BSdocs 同意)。您也可以只使用find选择一个元素。
标签: python python-3.x beautifulsoup