PDA

View Full Version : Không lấy được content của web sử dụng regex với c#



khong_tac
07-12-2013, 19:19
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Text.RegularExpressions;
using System.Management;
using System.IO;

namespace WindowsFormsApplication11
{
public partial class Form1 : Form
{
string regex_title = "<div class=\"title\">(.*?)</a>";
string regex_content = "<head>(.*?)</head>";
string htmlCode, content, title;
public Form1()
{
InitializeComponent();
textBox1.Text = "http://thethao.vnexpress.net/tin-tuc/cac-mon-khac/duong-thuy-vi-gianh-hc-vang-dau-tien-cho-viet-nam-2920478.html";
}

private void button1_Click(object sender, EventArgs e)
{
using (WebClient client = new WebClient())
{
string url = textBox1.Text;
this.htmlCode = client.DownloadString(url);

//Lay content
Regex regex_c = new Regex(this.regex_content, RegexOptions.IgnoreCase);
Match v_c = regex_c.Match(this.htmlCode);
if (v_c.Success)
{
this.content = v_c.Groups[1].Value;
richTextBox1.Text = this.content;
}
else
{
richTextBox1.Text = "NULL";
}
}
}
}
}

Em sử dụng đoạn mã trên đây để tách nội dung của web nằm trong thẻ <head> và </head> mà không được. Các bác xem giùm em có gì sai.

Cám ơn các bác.

dxt49
07-12-2013, 23:03
ban nghien cuu them HtlmAgilityPack nhe

QuanN
10-12-2013, 09:13
Dùng RegexOptions.Singleline (http://msdn.microsoft.com/en-us/library/yd1hzczs%28v=vs.110%29.aspx) mode để match mọi character, kể cả \n.

habogay
12-12-2013, 11:15
Nếu bạn parse dc json thì có thể thử link này

http://api1.hatforrent.com/api/get-special-content?key=102970812587044922224&c=TE09GAZFEI1386821180716&url=http://thethao.vnexpress.net/tin-tuc/cac-mon-khac/duong-thuy-vi-gianh-hc-vang-dau-tien-cho-viet-nam-2920478.html

Cái biến URL thay bằng 1 url của bài chi tiết

dxt49
13-12-2013, 13:48
ai lấy source tự động lấy tin viết = .net pm