我想通过Javascript读取不在同一个服务器上的网页,用了还是Ajax读取不了,用了Iframe报无权限访问网页的内容,大侠们有什么好的办法,指点指点
跨域读取确实存在权限问题,单纯靠JS解决不掉,你可以做个JS代理
就是在你服务器上放一个页面用于读取另一个服务器的网页,JS改请求自己服务器上的这个页面,这个页面的功能相当于一个代理,协助JS从其他服务器读取文件
当然也可以让这个页面接收参数,这样可以实现在客户端通过JS读取任意网页
1.JS不允许跨域操作,只能访问同一个域下面的资源
以下是网上的资源供你参考。
Code
private string GetWebContent(string Url)
{
string strResult="";
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
//声明一个HttpWebRequest请求
request.Timeout = 30000;
//设置连接超时时间
request.Headers.Set("Pragma", "no-cache");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream streamReceive = response.GetResponseStream();
Encoding encoding = Encoding.GetEncoding("GB2312");
StreamReader streamReader = new StreamReader(streamReceive, encoding);
strResult = streamReader.ReadToEnd();
}
catch
{
MessageBox.Show("出错");
}
return strResult;
}
Code
private void button1_Click(object sender, EventArgs e)
{
//要抓取的URL地址
string Url = "http://list.mp3.baidu.com/topso/mp3topsong.html?id=1#top2";
//得到指定Url的源码
string strWebContent = GetWebContent(Url);
richTextBox1.Text = strWebContent;
//取出和数据有关的那段源码
int iBodyStart = strWebContent.IndexOf("<body", 0);
int iStart = strWebContent.IndexOf("歌曲TOP500", iBodyStart);
int iTableStart = strWebContent.IndexOf("<table", iStart);
int iTableEnd = strWebContent.IndexOf("</table>", iTableStart);
string strWeb = strWebContent.Substring(iTableStart, iTableEnd - iTableStart + 8);
//生成HtmlDocument
WebBrowser webb = new WebBrowser();
webb.Navigate("about:blank");
HtmlDocument htmldoc = webb.Document.OpenNew(true);
htmldoc.Write(strWeb);
HtmlElementCollection htmlTR = htmldoc.GetElementsByTagName("TR");
foreach (HtmlElement tr in htmlTR)
{
string strID = tr.GetElementsByTagName("TD")[0].InnerText;
string strName = SplitName(tr.GetElementsByTagName("TD")[1].InnerText, "MusicName");
string strSinger = SplitName(tr.GetElementsByTagName("TD")[1].InnerText, "Singer");
strID = strID.Replace(".", "");
//插入DataTable
AddLine(strID, strName, strSinger,"0");
string strID1 = tr.GetElementsByTagName("TD")[2].InnerText;
string strName1 = SplitName(tr.GetElementsByTagName("TD")[3].InnerText, "MusicName");
string strSinger1 = SplitName(tr.GetElementsByTagName("TD")[3].InnerText, "Singer");
//插入DataTable
strID1 = strID1.Replace(".", "");
AddLine(strID1, strName1, strSinger1,"0");
string strID2 = tr.GetElementsByTagName("TD")[4].InnerText;
string strName2 = SplitName(tr.GetElementsByTagName("TD")[5].InnerText, "MusicName");
string strSinger2 = SplitName(tr.GetElementsByTagName("TD")[5].InnerText, "Singer");
//插入DataTable
strID2 = strID2.Replace(".", "");
AddLine(strID2, strName2, strSinger2,"0");
}
//插入数据库
InsertData(dt);
dataGridView1.DataSource = dt.DefaultView;
}