Форум программистов, компьютерный форум, киберфорум
C# для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.50/8: Рейтинг темы: голосов - 8, средняя оценка - 4.50
1 / 1 / 0
Регистрация: 09.09.2014
Сообщений: 120

Парсинг текста с html

25.07.2016, 22:37. Показов 1722. Ответов 4
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Хочу спарсить текст с скачанного html документа, но вообще не шарю как это сделать.

Есть какие либо идеи? Как я понимаю он находиться в этом блоке (см. скрин)

Также приложил сам html в архиве. Можете показать на коде пожалуйста.
Миниатюры
Парсинг текста с html  
Вложения
Тип файла: rar Архив WinRAR (4).rar (18.7 Кб, 5 просмотров)
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
25.07.2016, 22:37
Ответы с готовыми решениями:

Парсинг делают одновременно со скачиванием html, или в конце со скачанным html
Представим что html байт за байтом записывается в файл, Как правильнее сделать парсинг , после того как будет скачан полностью весь html,...

HTML парсинг
Здравствуйте. Столкнулся со следующей проблемой: Нужно сделать программу, которая парсит сайты (bash, IThappens) и выводит все цитаты...

Парсинг HTML
подскажите как вообще парсить HTML? не имел дела с этим вообще пока что... надо спарсить небольшую базу данных с сайта

4
Эксперт .NET
 Аватар для Usaga
14299 / 9384 / 1353
Регистрация: 21.01.2016
Сообщений: 35,380
26.07.2016, 03:14
sergiy1912, не смотря на то, что с HTML можно работать руками, я бы посоветовал использовать очень удобную библиотеку HtmlAgilityPack (можно поставить с помощью NuGet). Вот пример как ей пользоваться.

Добавлено через 2 минуты
Для выборки нужных узлов используется язык запросов XPath.
0
2810 / 1679 / 885
Регистрация: 14.04.2015
Сообщений: 5,723
26.07.2016, 09:02
ты бы лучше расписал конкретно, что тебе нужно, и не страницу прикреплял, а в явном виде отобразил бы нужный её кусок в развернутом виде, здесь же можно в сообщение вставлять код HTML. а в архив вложил бы свои наработки.
0
1 / 1 / 0
Регистрация: 09.09.2014
Сообщений: 120
27.07.2016, 22:23  [ТС]
Usaga, вот мой кусок который я спарсил
HTML5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
   <div class="part_text" style="display: block;" id="text-part-1">
                                            п»їOutcome 1<br>
1. Identify the current legislation, guidelines, policies and procedures for safeguarding the welfare of children and young people including e-safety?<br>
<br>
<span class='tab'></span>The current legislation, guidelines, policies and procedures are there to protect and keep the children safe from being harmed or by any type of risk. The 3 main policies which i am going to talk about mentioning the children’s act 2004; children act 1989 which is every child matters. Children act 1989: This act was brought to simplify the law to keep away any harm from the children and young people and to protect them. This simply tells people what responsibilities are which they need to know and how to work together as a team when a child abuse is suspected. In this act the local authorities have a general duty to safeguard and promote the welfare of children within their area who are in need. The children’s act (2004) - due to the death of Victoria climbie it had led the children act 2004 which is вЂ&#152;every child matters’. This includes the maximize opportunities and minimize the risk for all children’s. The outcomes of the keys are for every child matters; to stay safe and secure, to enjoy and achieve, to make positive contribution and to achieve an economic well-being.                                                               This act includes: The common assessment of framework to help agencies to identify the needs of the children The local authority’s children’s directors are responsible for education and children’s social services. Also the local safeguarding children’s boards ensure that the social services, NHS and education services. The police and other services which are involved in this services work together to help and protect the vulnerable children.<br>
<br>
<span class='tab'></span>Working with children and young people should have the following policies and procedures: A policy for the protection of a child who is under the age of 18 that mentions the responsibilities and is the reviewed yearly. A duty which to inform the independent safeguarding authority of any kind of paid worker, the volunteer or any other who is a threat to the children. To update the training on safeguarding for all member of staff, governors and volunteers. Senior member who is in charge of the safeguarding arrangements. Any effective risk of arrangements for CRB checks on all the adults who have                                        </div>
                                                                                                                                                <div class="part_text" id="text-part-2">
                                             regular or unsupervised access to the children until the age of 18. Up to date record on all the checks on staff, governors and volunteers. Contact details of parents or carers for all children under the age of 18.<br>
<br>
E-safety:<br>
<span class='tab'></span>Now a day’s many young people have an access to computers and mobile phones. They all have benefits for education, research, contacting family, friends even useful for shopping online. But there is also risks such as cyber bulling through text messages and emails on computers. It can reduce risks and help young people and children from not facing this to use it safely by having a restriction to the following types of points below: Making children aware of the dangers of these devices etc.<br>
<br>
A limited access to use the computer.<br>
<span class='tab'></span>Blocking any type of access or having a password to unsuitable sites. Also the school ensures that these sites will be blocked so it won’t be reaching in school computers and the children will be protected.<br>
<br>
2. Describe the roles of different agencies involved in safeguarding the welfare of children and young people?<br>
<br>
<span class='tab'></span>The main organization, services and professionals are mainly involved on safeguarding are several different services involved with the family, including their health, education, social servicing and voluntary agencies, each with their own area of responsibility. For example:<br>
<br>
Health services include:<br>
<span class='tab'></span>The health visitors- have a responsibility for the health development of children who are under the age of 5 General practitioners- have a responsibilities for the general health of registered patients in their local community <br>
<br>
Education services include:<br>
<span class='tab'></span>Teachers- they have responsibilities for the education and welfare of children and young people. The teachers work involves close observation of                                        </div>
                                                                                                                                                <div class="part_text" id="text-part-3">
                                             pupils on the classroom and this can frequently trigger concerns about health or welfare. Social services:<br>
<br>
<span class='tab'></span>They provide services for vulnerable children and their families. This might be because parents are struggling to care for their children or when families are trying to cope with challenging situations in their life like imprisonment or alcohol other drugs use as well. Social workers will always be involved in these matters involving the situations of abuse or harm with children or young people. Legal and criminal services include:<br>
<br>
<span class='tab'></span>Police- safety to protect the general public. This involves any criminal proceedings that may result from safeguarding situations. Probation officers- involving motioning people convicted of offences against children to ensure they do not continue to pose a threat. It is important that all these people work together as a team and share any type of information in order to coordinate and support for the child and young people and their family.<br>
<br>
Outcome 2:<br>
2.1) identify the signs and symptoms of common childhood illness. Name of illness<br>
Signs of illness<br>
Symptoms of illness<br>
Picture of illness<br>
Medical intervention<br>
<br>
Cold <br>
<br>
-Coughing, sneezing, sore throat and headache<br>
-Aching limbs, pain in swallowing, runny nose and hard to breathe. <br>
<br>
Attend GP<br>
Head lice<br>
<br>
-Tickling feeling of something in hair<br>
                                        </div>
                                                                                                                                                <div class="part_text" id="text-part-4">
                                            -excessive itching caused by allergic reaction<br>
-difficulty sleeping, head lice more active in dark<br>
-sores on head caused by itching.<br>
<br>
Attend GP<br>
Asthma<br>
-Difficulty breathing<br>
-difficult to exhale than inhale<br>
-tightness in chest<br>
<br>
-less energy during playing<br>
-coughing especially at night<br>
-wheezing, shortness of breath<br>
-chest tightness pain or pressure<br>
<br>
Attend GP<br>
<br>
Chicken pox<br>
<br>
-Itching and fever<br>
-Rash,<br>
-cough <br>
<br>
-Itching and fever=Temperature, aches and headache.<br>
- Rash=Spots appear in crops. They develop into small blisters and are itchy. They can be anywhere on the body. - cough=Dry cough and sore throat are common. <br>
<br>
Attend GP<br>
<br>
Mumps <br>
<br>
-Fever, headache and swelling  <br>
-Muscle aches, swollen and tender salivary glands under the ears on one or both sides, tiredness, partitas and loss of appetite. <br>
                                        </div>
                                                                                                                                                <div class="part_text" id="text-part-5">
                                            <br>
Attend GP for pain killers and make sure the child is kept hydrated<br>
<br>
Measles <br>
<br>
-fever, running nose, reddening of the eyes and headache<br>
-Runny nose, watery eyes, swollen eyelids, sneezing, tiredness, irritability and general lack of energy, aches and pains, poor appetite, dry cough, andВ* red-brown spotty rash. <br>
<br>
Medical attention from GP<br>
<br>
Upset stomach <br>
<br>
-Holding stomach <br>
-Pain in the stomach, along with a feeling of cramping, abdominal discomfort, and tenderness, fever and dizziness<br>
<br>
Attend GP<br>
Meningitis <br>
Fever, vomiting, muscle pain, headache<br>
-Cold hands and feet<br>
-pale blotchy skin, spots/rash<br>
-drowsy difficult to wake<br>
-stiff neck, confusion, dislike bright light<br>
-convulsions/ seizures<br>
<br>
Medical attention, plenty of fluids, painkillers and a lot of rest.<br>
<br>
2.2) describe the actions to take when children or young people are ill or injured<br>
<br>
Injury of child<br>
<br>
Signs of injury<br>
                                        </div>
                                                                                                                                                <div class="part_text" id="text-part-6">
                                            Symptoms of injury <br>
Picture of illness <br>
Medical intervention <br>
Head bump<br>
Head bump<br>
<span class='tab'></span>Head injury can occur right away or develop slowly over several hours or sometimes days. Even if the skull isn’t fractured the brain can bang against the inside of the skull and be bruised. The head may look fine but the problem can result the bleeding  Or swelling inside the skull.<br>
<br>
Seek medication from your GP<br>
unconsciousness<br>
Injury or illness<br>
Can cause confusion, drowsiness, dizziness, headache, light –headache and inability to speak or move any body parts<br>
<br>
The person will be unresponsive touch and sound them, if not any responsive call for an ambulance<br>
<br>
Cuts and grazes <br>
<br>
Painful and the gets red<br>
Cuts and grazes may bleed and feel slightly painful. The affected area will probably scab over while it is healing. <br>
<br>
See your GP as soon as possible <br>
<br>
Broken bone<br>
<br>
Pain and swelling <br>
A bone may look pale and clammy and feel faint, dizzy or sick.<br>
<br>
Accident and emergency department<br>
<br>
2.3 identify circumstances when children and young people might require                                        </div>
                                                                                                                                                <div class="part_text" id="text-part-7">
                                             urgent medical attention<br>
<br>
Reassure the child and stay with him/her<br>
Do not move the child unless it is needed to be <br>
If the child is unconscious they should be put into the recovery position Do not give anything to the child (food or drink)<br>
Keep the child warm for example by placing a warm blanket/jumper or a coat Ensure the other children in the area not at risk of being hurt<br>
<br>
2.4 describe the actions to take in response to emergency situations (a) Fires<br>
(b) Security incidents <br>
(c) Missing children or young people<br>
<br>
Fire:<br>
<span class='tab'></span>When a fire is set off the building needs to be evacuated quickly in a event of a fire to be caught. The emergency procedures should be visibly displayed. These procedures вЂ&#152;must’ be displayed in every each area of the school, with clear instructions about the location of the emergency exists and assembly points. Regular drills should be carried out to make sure that all the staff understand their own responsibilities and know what to do, information should be giving on: How to raise the alarm when a fire is set off<br>
<br>
What to do when you hear the fire alarm going on <br>
The route you are going to take<br>
Nearest assembly point you could see<br>
<span class='tab'></span>Registers should be available so the staff can make a check that all the children are safely out of the building It is very important to know the different routes of the building each and every area that you are working in. This is due of being in a different part of the building. It is also very important to have a test fire alarm to be trained and ready when a fire is really caught. <br>
<br>
Security:<br>
<br>
                                        </div>
 
   
......
 
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
                                        </div>
                                                                                                    <div id="full-text-text"></div>
Парсил так:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
HtmlWeb web = new HtmlWeb();
            HtmlAgilityPack.HtmlDocument d = new HtmlAgilityPack.HtmlDocument();
            d.Load(@"C:\sample.html");
 
 
            HtmlNodeCollection pads = d.DocumentNode.SelectNodes("//div[@class='format-container']");
  
 
            foreach (HtmlNode item in pads)
            {
                
                textBox1.Text = item.InnerHtml;
                System.IO.File.WriteAllText(@"asd.txt", textBox1.Text, Encoding.Default);
            }
Как мне сделать чтобы в тексте удалило абсолютно все теги (остался чистый текст)? Немного скоротил html, а то не влез.

Добавлено через 6 минут
Cделал
C#
1
2
string html = textBox1.Text;
                html = Regex.Replace(html, "<[^>]+>", string.Empty);
0
Эксперт .NET
 Аватар для Usaga
14299 / 9384 / 1353
Регистрация: 21.01.2016
Сообщений: 35,380
28.07.2016, 03:27
sergiy1912, у HtmlNode есть свойство InnerText...
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
28.07.2016, 03:27
Помогаю со студенческими работами здесь

HTML парсинг
Привет всем! Мне сказали код можно в 2 строки написать. Как правильно парсить HTML со страницы в C#? Допустим мне нужно с этого сайта в...

Парсинг html
Здравствуйте, нужно парсить логины и сообщения с определенного сайта Код с логином class=&quot;username&quot;...

Парсинг HTML
Здравствуйте, решил потренироваться в написании парсера Html страниц, но уперся в проблему и покуда не могу её решить. Для парсинга...

Парсинг HTML
Как ни пробовал, ничего не получается. Есть переменная string с текстом такого типа: ...

Парсинг HTML в вк
Пытаюсь спарсить Моб тел. класс=labeled делаю через HtmlAgilityPack var WebGet = new HtmlWeb(); var doc =...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
5
Ответ Создать тему
Новые блоги и статьи
Как дизайн сайта влияет на конверсию: 7 решений, которые реально повышают заявки
Neotwalker 08.03.2026
Многие до сих пор воспринимают дизайн сайта как “красивую оболочку”. На практике всё иначе: дизайн напрямую влияет на то, оставит человек заявку или уйдёт через несколько секунд. Даже если у вас. . .
Модульная разработка через nuget packages
DevAlt 07.03.2026
Сложившийся в . Net-среде способ разработки чаще всего предполагает монорепозиторий в котором находятся все исходники. При создании нового решения, мы просто добавляем нужные проекты и имеем. . .
Модульный подход на примере F#
DevAlt 06.03.2026
В блоге дяди Боба наткнулся на такое определение: В этой книге («Подход, основанный на вариантах использования») Ивар утверждает, что архитектура программного обеспечения — это структуры,. . .
Управление камерой с помощью скрипта OrbitControls.js на Three.js: Вращение, зум и панорамирование
8Observer8 05.03.2026
Содержание блога Финальная демка в браузере работает на Desktop и мобильных браузерах. Итоговый код: orbit-controls-threejs-js. zip. Сканируйте QR-код на мобильном. Вращайте камеру одним пальцем,. . .
SDL3 для Web (WebAssembly): Синхронизация спрайтов SDL3 и тел Box2D
8Observer8 04.03.2026
Содержание блога Финальная демка в браузере. Итоговый код: finish-sync-physics-sprites-sdl3-c. zip На первой гифке отладочные линии отключены, а на второй включены:. . .
SDL3 для Web (WebAssembly): Идентификация объектов на Box2D v3 - использование userData и событий коллизий
8Observer8 02.03.2026
Содержание блога Финальная демка в браузере. Итоговый код: finish-collision-events-sdl3-c. zip Сканируйте QR-код на мобильном и вы увидите, что появится джойстик для управления главным героем. . . .
Реалии
Hrethgir 01.03.2026
Нет, я не закончил до сих пор симулятор. Эта задача сложнее. Не получилось уйти в плавсостав, но оно и к лучшему, возможно. Точнее получалось - но сварщиком в палубную команду, а это значит, в моём. . .
Ритм жизни
kumehtar 27.02.2026
Иногда приходится жить в ритме, где дел становится всё больше, а вовлечения в происходящее — всё меньше. Плотный график не даёт вниманию закрепиться ни на одном событии. Утро начинается с быстрых,. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru