Как перебрать данные BS4 и правильно распечатать тег div - PullRequest
0 голосов
/ 31 января 2019

Я пытаюсь скопировать все данные на странице HTML, которая имеет определенный класс "chapter_header_styling" с BS4.

Это работало, когда я вручную вводил URL - но утомительно, когда есть несколько книги различные главы.Затем я создал другой сценарий, который будет генерировать все URL-адреса глав для книги и объединять их в текстовый файл bchap.txt (главы книги).

С тех пор я изменил файл и добавил различные точки останова, чтобыигнорировать отсутствие комментариев и неиспользуемых массивов / списка.Я сузил его до ###Comment##, где это не работает.Вероятно, это не правильно, но я не уверен ... У меня с этим все получалось, но я не могу понять, почему он не вставит данные mydivs в файл book.html.Если бы кто-то с большим опытом мог направить меня в правильном направлении, многое было бы оценено.

#mkbook.py
# coding: utf-8
from bs4 import BeautifulSoup
import requests

LINK = "https://codes.iccsafe.org/content/FAC2017"
pop = ""
#z = ""
chapters = open("bchap.txt",'r')
a = []
for aline in chapters:
  chap = aline
  #print (chap)
  #pop = ""
  pop = LINK+chap
  #print (pop)
  r = requests.get(pop)
  data = r.text
  #print(data)

  soup = BeautifulSoup(data, 'html.parser')

  mydivs = soup.findAll("div", {"class": ["annotator", "chapter_header_styling"]})

  f = open("BOOK.html","a")
  f.write("test <br/>")

########################################
#MY PROBLEM IS BELOW NOT PRINTING DIV DATA INTO TXT FILE
########################################
  for div in mydivs:
      print (div)
      z = str(div)
      print(z)  #doesn't printout...why???
      f.write(z)
  print len(mydivs)

  f.close()

chapters.close()



##############################################
## this is the old mkbook.py code before I looped it - inputing url 1 @ time
#
# coding: utf-8
from bs4 import BeautifulSoup
import requests
r = requests.get("https://codes.iccsafe.org/content/FAC2017/preface")
data = r.text
soup = BeautifulSoup(data, 'html.parser')
a = []
mydivs = soup.findAll("div",{"class":["annotator", 
"chapter_header_styling"]})
f = open("BOOK.html","a")
for div in mydivs:
  z = str(div)
  f.write(z)
f.close()
print len(mydivs) #outputs 1 if copied div data.

#######################################
#mkchap.py
# coding: utf-8
from bs4 import BeautifulSoup
import requests
r = requests.get("https://codes.iccsafe.org/content/FAC2017")
data = r.text
soup = BeautifulSoup(data, 'html.parser')
a = []
soup.findAll('option',{"value":True})
list = soup.findAll('option')
with open('bchap.txt', 'w') as filehandle:
  for l in list:
    filehandle.write(l['value'])
    filehandle.write("\n")
    print l['value']
#with open('bchap.txt', 'w') as filehandle:
#   filehandle.write("%s\n" % list)
filehandle.close()

1 Ответ

0 голосов
/ 31 января 2019

Кажется, проблема в том, что вы строите свой URL-адрес, используя неверный базовый URL-адрес.

LINK = "https://codes.iccsafe.org/content/FAC2017"

Если вы посмотрите на свой 1-й запрос, вы увидите это ясно.

print(pop)
print(r.status_code)

Выходы:

https://codes.iccsafe.org/content/FAC2017/content/FAC2017

404

После запуска кода для заполнения bchap.txt его вывод будет

/content/FAC2017
/content/FAC2017/legend
/content/FAC2017/copyright
/content/FAC2017/preface
/content/FAC2017/chapter-1-application-and-administration
/content/FAC2017/chapter-2-scoping-requirements
/content/FAC2017/chapter-3-building-blocks
/content/FAC2017/chapter-4-accessible-routes
/content/FAC2017/chapter-5-general-site-and-building-elements
/content/FAC2017/chapter-6-plumbing-elements-and-facilities
/content/FAC2017/chapter-7-communication-elements-and-features
/content/FAC2017/chapter-8-special-rooms-spaces-and-elements
/content/FAC2017/chapter-9-built-in-elements
/content/FAC2017/chapter-10-recreation-facilities
/content/FAC2017/list-of-figures
/content/FAC2017/fair-housing-accessibility-guidelines-design-guidelines-for-accessible-adaptable-dwellings
/content/FAC2017/advisory

Позволяет сначала изменить базовый URL и повторить попытку.

from bs4 import BeautifulSoup
import requests

LINK = "https://codes.iccsafe.org"
pop = ""
chapters = open("bchap.txt",'r')
a = []
for aline in chapters:
  chap = aline
  pop = LINK+chap
  r = requests.get(pop)
  print(pop)
  print(r.status_code)
chapters.close()

Выходы:

https://codes.iccsafe.org/content/FAC2017

404
...

почему?b'coz of \n.Если мы сделаем

print(repr(pop))

Он выдаст

'https://codes.iccsafe.org/content/FAC2017\n'

Вам придется также убрать \n.Окончательный код, который работал, это

from bs4 import BeautifulSoup
import requests
LINK = "https://codes.iccsafe.org"
pop = ""
chapters = open("bchap.txt",'r')
a = []
for aline in chapters:
  chap = aline
  pop = LINK+chap
  r = requests.get(pop.strip())
  data = r.text
  soup = BeautifulSoup(data, 'html.parser')
  mydivs = soup.findAll("div", class_="annotator chapter_header_styling")
  f = open("BOOK.html","a")
  for div in mydivs:
      z = str(div)
      f.write(z)
  f.close()
chapters.close()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...