从链接到文件下载 SVG 失败,因为不是有效的 base64?



所以我正在尝试下载一个看起来像base64的SVG图像,但失败了。URL比这长得多,但为了Veiwers,我缩短了它。

data:image/svg+xml;utf8,%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%20standalone%3D%22no%22%3F%3E%0A%3Csvg%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%20height%3D%2232%22%20version%3D%221.1%22%20viewBox%3D%220%200%20320%20320%22%20wid3A%20%20%3Crect%20height%3D%22320%22%20id%3D%22rect%22%20rx%3D%2251.2%22%20width%3D%22320%22%20x%3D%220%22%20y%3D%220%2F%3E%0A%20%20%20%20%3CclipPath%20id

%3D%22clip%22%3E%0A%20%20%20%20%20%20%20xlink%3Ahref%3D%22%23rect%22%2F%3E%0A%20%20%20%20%3C%2FclipPath%3E%0A%20%20%3C%2Fdefs%3E%0A%20%20%3Cuse%20fill%3D%22%23FFFC00%22%20stroke%3D%22black%22%20stroke-

法典:

foreach (var username in File.ReadAllLines("/Users/admin/Desktop/snap-scraper/snap-scraper/snapchats.txt"))
{
Console.WriteLine($"Attempting to grab QR for {username}");
driver.Navigate().GoToUrl($"https://snapchat.com/add/{username}");
Thread.Sleep(1000);
var htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(driver.PageSource);
var image = htmlDocument.DocumentNode.SelectSingleNode("//img");
if (image == null || !image.Attributes.Contains("src"))
{
Console.WriteLine($"Something went wrong for {username}");
continue;
}
Console.WriteLine($"Got the QR for {username} yay");
var src = image.Attributes.Where(x => x.Name == "src").First().Value;
string filePath = $"/Users/admin/Desktop/snap-scraper/snap-scraper/images/{username}.jpg";
File.WriteAllBytes(filePath, Convert.FromBase64String(src.Replace("-", "")));
}

这不是Base64.这是URL Encoding.如果粘贴编码的 URL,则可以在 URL 解码器工具中看到此信息。

由于 SVG 由XML format组成,因此它们不需要编码。

您可以使用 WebUtility.UrlDecode(String( 对字符串进行解码,然后使用 Encoding.GetBytes(String( 将其转换为字节,将字节写入磁盘。

例:

foreach (var username in File.ReadAllLines("/Users/admin/Desktop/snap-scraper/snap-scraper/snapchats.txt"))
{
Console.WriteLine($"Attempting to grab QR for {username}");
driver.Navigate().GoToUrl($"https://snapchat.com/add/{username}");
Thread.Sleep(1000);
var htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(driver.PageSource);
var image = htmlDocument.DocumentNode.SelectSingleNode("//img");
if (image == null || !image.Attributes.Contains("src"))
{
Console.WriteLine($"Something went wrong for {username}");
continue;
}
Console.WriteLine($"Got the QR for {username} yay");
var src = image.Attributes.Where(x => x.Name == "src").First().Value;
string filePath = $"/Users/admin/Desktop/snap-scraper/snap-scraper/images/{username}.svg"; // This was .jpg
// URL Decode Image - Remember to strip the start of the data url e.g. data:image/svg xml;utf8,
string svg = WebUtility.UrlDecode(src).replace("data:image/svg xml;utf8,", "");
// Convert SVG to byte array
byte[] svgBytes = Encoding.UTF8.GetBytes(decodedUrl);
// Write to byte array to disk
File.WriteAllBytes(filePath, svg);
}

最新更新