从网页获取链接

2024-05-16 05:50:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从这个网页得到所有的项目链接(网址)到一个文本文件,以分隔符(换言之,一个这样的列表:“item#1”“item#2”等

http://dota-trade.com/equipment?order=name是一个网页,如果你向下滚动,它会一直显示大约500-1000个项目。在

我必须使用什么编程语言,或者怎样才能做到这一点。我也有使用imacros的经验。在


Tags: 项目namecomhttp网页列表链接order
2条回答

你需要下载HtmlAgilityPack

using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            WebClient wc = new WebClient();
            var sourceCode = wc.DownloadString("http://dota-trade.com/equipment?order=name");
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(sourceCode);
            var node = doc.DocumentNode;
            var nodes = node.SelectNodes("//a");
            List<string> links = new List<string>();
            foreach (var item in nodes)
            {
                var link = item.Attributes["href"].Value;
                links.Add(link.Contains("http") ? link : "http://dota-trade.com" +link);
            }
            int index = 1;
            while (true)
            {
                sourceCode = wc.DownloadString("http://dota-trade.com/equipment?order=name&offset=" + index.ToString());
                doc = new HtmlDocument();
                doc.LoadHtml(sourceCode);
                node = doc.DocumentNode;
                nodes = node.SelectNodes("//a");
                var cont = node.SelectSingleNode("//tr[@itemtype='http://schema.org/Thing']");
                if (cont == null) break; 
                foreach (var item in nodes)
                {
                    var link = item.Attributes["href"].Value;
                    links.Add(link.Contains("http") ? link : "http://dota-trade.com" + link);
                }
                index++;
            }
            System.IO.File.WriteAllLines(@"C:\Users\Public\WriteLines.txt", links);
        }
    }
}

我建议使用任何支持正则表达式的语言。我经常使用ruby,所以我会这样做:

require 'net/http'
require 'uri'

uri = URI.parse("http://dota-trade.com/equipment?order=name")

req = Net::HTTP::Get(uri.path)
http = Net::HTTP.new(uri.host, uri.port)
response = http.request(request)

links = response.body.match(/<a.+?href="(.+?)"/)

这太离谱了,但是links[0]应该是一个匹配对象,后面的每个元素都是匹配的。在

^{pr2}$

最后一行应该转储您想要的内容,但可能不包括主机。如果要包含主机,请执行以下操作:

^{3}$

请记住这是未经测试的。在

相关问题 更多 >