繁体   English   中英

无法使用请求从网站获取一些数字

[英]Can't fetch some numbers from a website using requests

我正在尝试使用请求从网页中获取一些数字。 那里可用的数字在图像中。 到目前为止,我编写的脚本可以show我使用PIL库的数字,但无法打印它们。

网站地址

提交按钮上方可见的数字如下:

在此处输入图像描述

到目前为止我已经尝试过:

import io
import requests
from PIL import Image
from bs4 import BeautifulSoup
from urllib.parse import urljoin

base = 'http://horoscope.horoscopezen.com/'
url = 'http://horoscope.horoscopezen.com/archive2.asp?day=2&month=1&year=2022&sign=1#.Xy07M4oza1v'

def get_numbers(link):
    r = requests.get(link)
    soup = BeautifulSoup(r.text,"lxml")
    image_links = [urljoin(base,td['src']) for td in soup.select("td > img[src^='secimage.asp?']")]
    for image_link in image_links:
        r = requests.get(image_link)
        img = Image.open(io.BytesIO(r.content))
        img.show()
        break

if __name__ == '__main__':
    get_numbers(url)

如何从该站点获取数字?

您不需要在这里使用 OCR。 图像本身由每个数字的单独图像组成,通过解析图像链接可以得到整个数字。 图片链接的形式是http://horoscope.horoscopezen.com/secimage.asp?I=1&N=595A5C585A5C看起来I=参数是数字的索引,而N=参数是整数。 翻译似乎如下:

56 -> 9
57 -> 8
58 -> 7
59 -> 6
5A -> 5
5B -> 4
5C -> 3
5D -> 2
5E -> 1
5F -> 0

请注意,这些数字采用十六进制编码(所有字符都是 0-9,AF)。 由于 0x56 对应于 9,0x5F 对应于 0(并且 0x56 + 9 == 0x5F),因此我们可以使用公式9 - hex_num + 0x56来获得数字。 例如,56 将转换为9 - 0x56 + 0x56 = 9 ,而 5E 将转换为9 - 0x5E + 0x56 = 9 - 8 = 1

因此,您可以更改代码以使用以下方式打印整个数字:

def url_to_number(url):
    all_digits = []
    # We want the encoded number, find '&N=' and get the characters after it
    N = url[url.find('&N=') + 3:]
    # loop the characters in pairs
    for i in range(0, len(N), 2):
        digit = 9 - int(N[i:i+2], 16) + 0x56
        all_digits.append(digit)
    return all_digits

digit = 9 - int(N[i:i+2], 16) + 0x56进行了我前面提到的转换。 int(N[i:i+2], 16)将数字从字符串转换为 int,因为它是以 16 为基数(十六进制)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM